Echo Server based on the legacy EthernetNetIf libraries used for a performance comparison with the new networking libraries

Dependencies:   EthernetNetIf mbed

Fork of EchoServer by ryosuke kojima

Revision:
0:fcd581e3ad7d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/EchoServer.cpp	Mon Jun 13 06:47:43 2011 +0000
@@ -0,0 +1,60 @@
+#include "EchoServer.h"
+#include "lwip/ip_addr.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);
+        }
+    }
+}