UDP server example project for the NetworkAPI library
Dependencies: EthernetInterface NetworkAPI mbed-rtos mbed
Fork of TCP_Client_Example by
Diff: main.cpp
- Revision:
- 12:f1bed576c7ac
- Parent:
- 11:f4d618b8141f
--- a/main.cpp Thu Sep 27 09:32:23 2012 +0000 +++ b/main.cpp Thu Sep 27 09:45:58 2012 +0000 @@ -1,10 +1,10 @@ #include "mbed.h" #include "EthernetInterface.h" - + #include "NetworkAPI/buffer.hpp" #include "NetworkAPI/ip/address.hpp" -#include "NetworkAPI/tcp/socket.hpp" - +#include "NetworkAPI/udp/socket.hpp" + int main() { @@ -12,34 +12,44 @@ interface.init(); interface.connect(); printf("IP Address is %s\n\r", interface.getIPAddress()); - - int result; - - network::tcp::Socket socket; + + network::udp::Socket socket; network::Buffer buffer(256); - std::string request("GET /media/uploads/donatien/hello.txt HTTP/1.1\r\nHost: %s\r\n\r\n"); - + if (socket.open() < 0) { - printf("Failed to open TCP Socket\n\r"); - return -1; - } - - if (socket.connect("mbed.org", 80) < 0) { - printf("Failed to connect with mbed.org\n\r"); + printf("Failed to open UDP Socket\n\r"); return -1; } - - if (socket.write((void *)request.data(), request.size()) < 0) { - printf("Failed to write HTTP request\n\r"); - return -1; + + if (socket.bind(42) < 0) { + printf("Failed to bind UDP Socket to port 42\n\r"); } - - do - { - result = socket.read(buffer); - printf("Received %d bytes:\n\r%s\n\r", result, (char *)buffer.data()); - } while(result > 0); - - socket.close(); + + while (true) { + int result = socket.receive(buffer); + + switch (result) { + case -1: + printf("Failed to read from UDP Socket\n\r"); + return -1; + + case 0: + printf("Nothing received...?\n\r"); + continue; + + default: + printf("Received %d bytes from %s:%d\n\r", result, + socket.getRemoteEndpoint().getAddress().toString().c_str(), + socket.getRemoteEndpoint().getPort()); + + printf("Message: %s\n\r", (char *)buffer.data()); + + if (!socket.getRemoteEndpoint().getAddress().isEmpty()) { + socket.send(buffer, socket.getRemoteEndpoint()); + } + continue; + } + } + return 0; } \ No newline at end of file