ManualResetEvent reviceManager = new ManualResetEvent(false);
1 Public void args_completed (Object sender, socketasynceventargs E) 2 {3 // The Listener completes the client's request, but the listener returns a new socket 4 var clientsocket = E. acceptsocket; 5 // the startup thread obtains the message sent from the client 6 if (clientsocket = NULL) return; 7 8 // This part is divided into receiving Message 9 var T = new thread (getclientmsg ); 10 // set the thread to the background thread 11 T. isbackground = true; 12 // start thread 13 T. start (clientsocket); 14 // display information 15 showmsg (clientsocket. remoteendpoint + "online"); 16 // sets the event status to terminated, and allows one or more threads to wait for 17 managers to continue. set (); 18}
We recommend that you start asynchronous Service Listening Based on C # socket BASICS (1.
1 private void getclientmsg (Object socket) 2 {3 var socketclient = socket as socket; 4 If (socketclient = NULL) return; 5 while (true) 6 {7 Try 8 {9 revicemanager. reset (); 10 var bytes = new byte [1024*1024*4]; 11 var receiveargs = new socketasynceventargs ();
// Set the buffer 12 receiveargs. setbuffer (bytes, 0, bytes. Length); 13 receiveargs. Completed + = receiveargs_completed;
// Start receiving 14 socketclient asynchronously. receiveasync (receiveargs); 15 revicemanager. waitone (); 16} 17 catch (exception ex) 18 {19 20 // display exception message 21 showmsg (ex. message );
22}
}
}
Receives a message completion callback event.
1 void receiveargs_completed (Object sender, socketasynceventargs E) 2 {3 var socketclient = sender as socket; 4 var bytes = E. buffer; 5 showmsg (socketclient. remoteendpoint + "said:" + system. text. encoding. utf8.getstring (bytes); 6 revicemanager. set (); 7}
To be continued. Next article: Socket BASICS (iii) client and server establish connection and receive messages
Gaobing Source: http://gaobing.cnblogs.com tips: The copyright of this article belongs to the author and blog Park, welcome to reprint, but without the author's consent must retain this paragraph of the statement, and in the Article Page clearly given the original connection, otherwise, you are entitled to pursue legal liability.