![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
server/client
Dependencies: mbed NetServicesMin
Diff: tcp_server.cpp
- Revision:
- 0:432b571e11a3
- Child:
- 1:6e61ee662fd3
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tcp_server.cpp Sun Feb 19 06:21:50 2012 +0000 @@ -0,0 +1,120 @@ +#include "mbed.h" +#include "config.h" +#include "tcp_server.h" +#include "tcp_client.h" + +TCPSocket listenSock; +TCPSocket* recieveSock; +Host client; +IpAddr inCommingIp; + +extern bool isHostConnected; +int serverInit(void) +{ + listenSock.setOnEvent(&onServerListnerEvent) ; + + printf("Bindding...\r\n") ; + + if ( listenSock.bind(Host(IpAddr(), kServerPort)) != ETH_OK ){ + printf("Bindding Error.\r\n") ; + return -1 ; + } + + printf("Listen...\r\n"); + + if ( listenSock.listen() != ETH_OK ){ + printf("Listen Error.\r\n") ; + return -1 ; + } + return 0; +} + +//Listner Event +void onServerListnerEvent(TCPSocketEvent e) +{ + printf("server ---IN TCPSocketEvent ---\r\n"); + + if ( e == TCPSOCKET_ACCEPT ){ + printf("Listening: TCP Socket Accepted\r\n"); + + if ( listenSock.accept(&client, &recieveSock) != TCPSOCKET_OK ) { + printf("onTcpSocketEvent Error \r\n"); + return; + } + + recieveSock->setOnEvent(&onServerRecievetEvent); + + //Get Client Side IP Address + inCommingIp = client.getIp(); + printf("Controler IP Address is [%d.%d.%d.%d].\r\n", inCommingIp[0], inCommingIp[1], inCommingIp[2], inCommingIp[3]); + } + + printf("server --- OUT TCPSocketEvent ---\r\n\r\n") ; + } + +void onServerRecievetEvent(TCPSocketEvent e) +{ + printf("server --- IN ConnectEvent ---\r\n"); + + + switch(e) + { + case TCPSOCKET_CONNECTED: + printf("Connected to host.\r\n") ; + break; + + case TCPSOCKET_WRITEABLE: + printf("Can write data to buf.\r\n"); + break; + + case TCPSOCKET_READABLE: + printf("Data in buf.\r\n"); + char buf[128] ; + while ( int len = recieveSock->recv(buf,sizeof(buf)) ) { + + int err =tcpSend(buf, len); + + recieveDump(buf,len); + } + break; + + case TCPSOCKET_CONTIMEOUT: + printf("Connection timed out.\r\n"); + break ; + + case TCPSOCKET_CONRST: + printf("Connection was reset by remote host.\r\n"); + break ; + + case TCPSOCKET_CONABRT: + printf("Connection was aborted.\r\n") ; + break ; + + case TCPSOCKET_ERROR: + printf("Unknown error.\r\n") ; + break ; + + case TCPSOCKET_DISCONNECTED: + printf("Tcp Socket Disconnected\r\n") ; + recieveSock->close() ; + break; + } + printf("--- OUT ConnectEvent ---\r\n\r\n"); +} + +void recieveDump(char *data , int length){ + printf("size = %d\n -- -id\n",length); + + for(int i=0;i<16;i++) printf("%d:%0x ",i,data[i]); + printf("\n--- data\n"); + + int count=0; + for(int i=0;i<(length-16);i++){ + printf("%02d:%02x ",i,data[16+i]); + if( count==15 ) {count=0; printf("\n");} + else count++; + } + + printf("\n---frame end\n"); +} +