An Echo server as described in RFC862. Written as a learning exercise for using Donatien's network stack. Hopefully of some use to others to get started with socket programming.

Dependencies:   mbed

Revision:
0:c4e397ba6a9d
diff -r 000000000000 -r c4e397ba6a9d EchoServer.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/EchoServer.cpp	Sat Jun 12 19:05:52 2010 +0000
@@ -0,0 +1,60 @@
+#include "EchoServer.h"
+
+EchoServer::EchoServer() {
+    // Create the sockets and set the callbacks
+    tcpSock = new TCPSocket;
+    tcpSock->setOnEvent(this, &EchoServer::onNetTcpSocketEvent);
+    udpSock = new UDPSocket;
+    udpSock->setOnEvent(this, &EchoServer::onNetUdpSocketEvent);
+}
+
+EchoServer::~EchoServer() {
+    // Delete the sockets on destruction
+    delete tcpSock;
+    delete udpSock;
+}
+
+void EchoServer::bind(int tcpPort, int udpPort) {
+    // bind and listen on TCP
+    tcpSock->bind(Host(IP_ADDR_ANY, tcpPort));
+    tcpSock->listen();
+    // bind UDP
+    udpSock->bind(Host(IP_ADDR_ANY, udpPort));
+}
+
+void EchoServer::onNetTcpSocketEvent(TCPSocketEvent e) {
+    // We're only interested in the ACCEPT event where we need to accept
+    // the incoming connection
+    if ( e == TCPSOCKET_ACCEPT ) {
+        TCPSocket* tcpClientSocket;
+        Host client;
+        if ( tcpSock->accept(&client, &tcpClientSocket) ) {
+            printf("onNetTcpSocketEvent : Could not accept connection.\r\n");
+            return; //Error in accept, discard connection
+        }
+        // We can find out from where the connection is coming by looking at the
+        // Host parameter of the accept() method
+        IpAddr clientIp = client.getIp();
+        printf("Incoming TCP connection from %d.%d.%d.%d\r\n", clientIp[0], clientIp[1], clientIp[2], clientIp[3]);
+        // Create TCPEchoHandler and pass client socket
+        TCPEchoHandler* tcpHandler = new TCPEchoHandler(tcpClientSocket); //TCPSocket ownership is passed to handler
+        // The handler object will destroy itself when done, or will be destroyed on Server destruction
+    }
+}
+
+void EchoServer::onNetUdpSocketEvent(UDPSocketEvent e) {
+    // We're only interested in the READABLE event (it's the only one)
+    if ( e == UDPSOCKET_READABLE ) {
+        // No need for a handler for UDP - set up a buffer and check client
+        char buff[128];
+        Host client;
+        IpAddr clientIp = client.getIp();
+        printf("Incoming UDP connection from %d.%d.%d.%d\r\n", clientIp[0], clientIp[1], clientIp[2], clientIp[3]);
+        // Keep reading while there's data to be read
+        while ( int len = udpSock->recvfrom(buff, 128, &client) ) {
+            if ( len > 0 )
+                // If there's data, send it straight back out
+                udpSock->sendto(buff, len, &client);
+        }
+    }
+}