Robert Cook
/
NetworkAnimator
EchoServer.cpp
- Committer:
- robertcook
- Date:
- 2012-06-13
- Revision:
- 0:32a0996dff0f
File content as of revision 0:32a0996dff0f:
#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(IpAddr(192,168,1,128), tcpPort)); tcpSock->listen(); // bind UDP udpSock->bind(Host(IpAddr(192,168,1,128), 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); } } }