To write a high-performance socket server, it is undesirable to assign separate processing threads to each socket that is received, and the server simply cannot cope when the number of connections is large. To respond to a large number of connections, you need to use the IOCP (completion port) to replace and process the response.
The System.Net.Sockets.Socket class of the. NET Framework has a set of xxxasync methods that encapsulate the processing of IOCP for writing high-performance Socket applications, Xxxasync This group of methods needs to be used in conjunction with the SocketAsyncEventArgs class, here is the MSDN reference, which has a detailed example:
Http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socketasynceventargs.aspx
Socket class Xxxasync method, use more complex, need time to digest the above example, the actual writing required operation.
During the Web server programming process. Requires the use of asynchronous technology. Where to use async:
1, listening socket, need to wait for client access. This is required for a thread dedicated to monitoring (accept method)
2. Once the client is connected, the communication socket needs a thread to listen to the buffer in order to communicate with the client. Include Receive and send.
Write some of your own understanding.
1, using the asynchronous method provided in the socket class: Acceptasync. Create a Listener method
This method needs to be repeated in the callback function to ensure the listener.
private void Startaccept (SocketAsyncEventArgs accepteventarg) { if (Accepteventarg = = null) //initialized with { Accepteventarg = new SocketAsyncEventArgs (); accepteventarg.completed + = new eventhandler<socketasynceventargs> (onacceptcompleted); callback function Instantiation } else //circular call needs to clean up the object. Set the AcceptSocket property to null. Wait for access to the new connection { accepteventarg.acceptsocket = null; } bool bl = This.listenSocket.AcceptAsync (Accepteventarg); The Async method can only receive one connection at a time. You need to loop the call if (!BL) {this . Processaccept (Accepteventarg); } }
callback function (with format OH) This e variable contains a lot of stuff oh.
private void Onacceptcompleted (object sender, SocketAsyncEventArgs e) { Console.WriteLine ("There is a client connected up"); Startaccept (e); It is important that the method be called in a loop. Implement listening }
2, in the callback function. Use the Async methods provided by the socket class: Receiveasync and SendAsync. Receive and send data asynchronously
The C # SocketAsyncEventArgs class uses