ArticleDirectory
- Reconstruction version:
- Summary
Although multithreading is rarely used in development, you must admit that you cannot leave it alone.
Next I wrote a blog post (something unknown about ASP. NET (3). Basically I can implement a mini server, but there are also some shortcomings:
If the client rapidly connects, the server will soon be overwhelmed.
Fortunately, the socket class implements the asynchronous call mode of the. NET Framework. Using this mode, the thread pool can make the server better serve the incoming requests.
Reconstruction version:
Class Program { Private Const Int Connectionqueuelength = 4 ; Private Const Int Listenport = 1234 ; Private Const Int Maxconnectionhandlers = 4 ; Static Void Handleconnection (iasyncresult AR ){ // Asyncresult = (asyncresult) Ar; Socket listener =(Socket) Ar. asyncstate; socket newconnectin = Listener. endaccept (AR ); Byte [] MSG = encoding. utf8.getbytes ( " Hello World " ); Newconnectin. beginsend (MSG, 0 , MSG. length, socketflags. None, New Asynccallback (program. closeconnection), newconnectin );} Static Void Closeconnection (iasyncresult AR) {Socket socket = Ar. asyncstate As Socket; If (Socket! = Null ) {Socket. Close ();}} Static Void Main ( String [] ARGs) {socket listensocket = New Socket (addressfamily. InterNetwork, sockettype. Stream, protocoltype. TCP); listensocket. BIND ( New Ipendpoint (IPaddress. Any, listenport); listensocket. Listen (connectionqueuelength ); For ( Int I = 0 ; I <maxconnectionhandlers; I ++ ) {Listensocket. beginaccept ( New Asynccallback (program. handleconnection), listensocket) ;}console. readkey ();}}
In this way, our server is more efficient, and it sends data back from the thread pool.
Note that the asynchronous call here (New asynccallback (program. closeconnection)) Uses a callback method to close the connection, because in order to make the server more efficient, it makes no sense to let the listening thread wait in endsend, because it will block the current thread.
Summary
The server stage is over. I believe you have some knowledge about it. Next I will talk about how to implement multithreading in ASP. NET.