/* TCP_Ser.c: TCP Server Demo program for uPAC-7186 series A server listen and wait to handle the coming connections Compiler: BC++ 3.1, Turbo C++ 1.01 (3.01) MSVC 1.52 Compile mode: large Project: Server.C ..\..\..\Lib\uPAC5000.lib ..\..\lib\tcp_dm32.lib Details: Setup a server, wait for connections. While a connection has been established, receive data from clients. [Jan 06, 2012] by Liam */ #include #include #include #include #include "..\..\..\lib\upac5000.h" #include "..\..\lib\Tcpip32.h" unsigned short service_port[2]={10000, 10001}; // define the service port for Server struct timeval seltime={0, 20}; // 2000ns=2ms unsigned ActiveSkt[2]={0, 0}; STOPWATCH swSocket[NCONNS], swTimer; ulong ulSocketTimeout=86400000UL; // Sets the socket communication timeout value. // If the timeout expires, the connection will be released // Time unit: ms fd_set rfds; // set of socket file descriptors for reading typedef struct tagSocket_State { int active; // socket is active int init; // socket just initiated struct sockaddr_in sin; // client address unsigned port; // port number int be_master_socket; // is master socket } socket_state; socket_state socket_state_table[NCONNS]; // sockets state table struct ip host_ip; int TCP_server_initial(void) { /* Return: 0: ok. <>0: error */ int i, iRet; if((iRet=NetStart())<0) return iRet; FD_ZERO(&rfds); for(i=0; i=16) ActiveSkt[1]|=1<<(err-16); else ActiveSkt[0]|=1<=16) ActiveSkt[1]&=~(1<<(current_socket-16)); else ActiveSkt[0]&=~(1<=0) continue; // success if(err==-1) Print("cannot create a socket on port: %d\r\n", service_port[i]); if(err==-2) Print("cannot bind to port %d\r\n", service_port[i]); if(err==-3) Print("cannot listen on port %d\r\n", service_port[i]); Nterm(); return; } //Step 3: Service loop: 3-1: wait on sockets and accept // 3-2: perform service, receive and send T_StopWatchStart(&swTimer); while(!iQuit) // service loop { if(Kbhit() && Getch()==27) // press 'ESC' key to terminate the program { iQuit=1; } // check the socket timeout at 50 ms intervals if(T_StopWatchGetTime(&swTimer)>=50) { T_StopWatchStart(&swTimer); if(ulSocketTimeout) { static int iSocket=0; int mask; if(iSocket>=16) mask=ActiveSkt[1]&(1<<(iSocket-16)); else mask=ActiveSkt[0]&(1<=ulSocketTimeout) { Print("Socket timeout, socket#%d closed\r\n", iSocket); TCP_close_socket(iSocket); } iSocket++; if(iSocket>=NCONNS) iSocket=0; } } YIELD(); //Step 3-1: Wait for activity on sockets and accept a connection err=wait_to_accept(); if(err==-1) { Print("selectsocket error\r\n"); break; } else if(err==-2) continue; //selectsocket() time out else if(err==-3) Print("accept error %d\r\n"); //Step 3-2: perform service, receive and send for(i=0; i