Select is an old but proven Socket mode that allows you to write socket programs in message-driven mode. There are many examples of C ++ on the Internet, but there are very few examples of C.
Code:
Namespace server {class program {// thread signal. public static manualresetevent alldone = new manualresetevent (false); Private Static socket handler = NULL; Private Static arraylist g_clisocketarr = new arraylist (); Private Static object thislock = new object (); public Program () {} public static void startlistening () {// data buffer for incoming data. byte [] bytes = new byte [1024]; IPaddress = IPaddress. parse ("192.168.1.71"); // ipendpoint localendpoint = new ipendpoint (IPaddress, 11000); // create a TCP/IP socket. socket listener = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); // bind the socket to the local endpoint and listen for incoming connections. try {listener. BIND (localendpoint); listener. listen (100); // start an asynchronous socket to listen for connections. console. writeline ("waiting for a connection... "); thread worker = new thread (New threadstart (workerthread); // create a thread to process the worker request. start (); While (true) {socket sclient = listener. accept (); console. writeline ("there is a new connection. "); g_clisocketarr.add (sclient) ;}} catch (exception e) {console. writeline (E. tostring ();} console. writeline ("\ npress enter to continue... "); console. read ();} public static void workerthread () {socket socket1 = NULL; arraylist readlist = new arraylist (); // readlist. add (socket0); While (true) {lock (thislock) {readlist. clear (); For (INT I = 0; I <g_clisocketarr.count; I ++) {readlist. add (g_clisocketarr [I]) ;}} if (readlist. count <= 0) {thread. sleep (100); continue;} Try {socket. select (read list, null, null, 500); For (INT I = 0; I <readlist. count; I ++) {socket1 = (socket) readlist [I]; console. writeline ("there is a new message from client. "); byte [] buffer = new byte [1024]; int reclen = socket1.receive (buffer); If (reclen> 0) {// reclen = socket1.receive (buffer );} else {// If 0 is returned, the client has been disconnected. You must disable this socket and then clear the console from the connection pool. writeline ("rece 0 length. "); For (int ii = 0; II <g_clisocketarr.count; II ++) {socket S = (socket) g_clisocketarr [II]; If (S = socket1) g_clisocketarr.removeat (II);} socket1.shutdown (socketshutdown. both); socket1.close (); break;} socket1.send (buffer, reclen, socketflags. none) ;}} catch (socketexception e) {console. writeline ("{0} error code: {1 }. ", E. message, E. errorcode); For (int ii = 0; II <g_clisocketarr.count; II ++) {socket S = (socket) g_clisocketarr [II]; If (S = socket1) g_clisocketarr.removeat (II);} socket1.shutdown (socketshutdown. both); socket1.close () ;}} static void main (string [] ARGs) {startlistening ();}}}