Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
EchoServer.cpp
00001 #include "EchoServer.h" 00002 00003 char* screenBufA; 00004 00005 EchoServer::EchoServer(char* scrbuf) { 00006 // Create the sockets and set the callbacks 00007 tcpSock = new TCPSocket; 00008 tcpSock->setOnEvent(this, &EchoServer::onNetTcpSocketEvent); 00009 udpSock = new UDPSocket; 00010 udpSock->setOnEvent(this, &EchoServer::onNetUdpSocketEvent); 00011 screenBufA = scrbuf; 00012 } 00013 00014 EchoServer::~EchoServer() { 00015 // Delete the sockets on destruction 00016 delete tcpSock; 00017 delete udpSock; 00018 } 00019 00020 void EchoServer::bind(int tcpPort, int udpPort) { 00021 // bind and listen on TCP 00022 tcpSock->bind(Host(IpAddr(192,168,1,128), tcpPort)); 00023 tcpSock->listen(); 00024 // bind UDP 00025 udpSock->bind(Host(IpAddr(192,168,1,128), udpPort)); 00026 } 00027 00028 void EchoServer::onNetTcpSocketEvent(TCPSocketEvent e) { 00029 // We're only interested in the ACCEPT event where we need to accept 00030 // the incoming connection 00031 if ( e == TCPSOCKET_ACCEPT ) { 00032 TCPSocket* tcpClientSocket; 00033 Host client; 00034 if ( tcpSock->accept(&client, &tcpClientSocket) ) { 00035 printf("onNetTcpSocketEvent : Could not accept connection.\r\n"); 00036 return; //Error in accept, discard connection 00037 } 00038 // We can find out from where the connection is coming by looking at the 00039 // Host parameter of the accept() method 00040 IpAddr clientIp = client.getIp(); 00041 printf("Incoming TCP connection from %d.%d.%d.%d\r\n", clientIp[0], clientIp[1], clientIp[2], clientIp[3]); 00042 // Create TCPEchoHandler and pass client socket 00043 TCPEchoHandler* tcpHandler = new TCPEchoHandler(tcpClientSocket, screenBufA); //TCPSocket ownership is passed to handler 00044 // The handler object will destroy itself when done, or will be destroyed on Server destruction 00045 } 00046 } 00047 00048 void EchoServer::onNetUdpSocketEvent(UDPSocketEvent e) { 00049 // We're only interested in the READABLE event (it's the only one) 00050 if ( e == UDPSOCKET_READABLE ) { 00051 // No need for a handler for UDP - set up a buffer and check client 00052 char buff[128]; 00053 Host client; 00054 IpAddr clientIp = client.getIp(); 00055 printf("Incoming UDP connection from %d.%d.%d.%d\r\n", clientIp[0], clientIp[1], clientIp[2], clientIp[3]); 00056 // Keep reading while there's data to be read 00057 while ( int len = udpSock->recvfrom(buff, 128, &client) ) { 00058 if ( len > 0 ) 00059 // If there's data, send it straight back out 00060 udpSock->sendto(buff, len, &client); 00061 } 00062 } 00063 }
Generated on Wed Jul 13 2022 09:03:52 by
