Generally, an independent acceptor thread is used to listen to client connections. After receiving client connection requests, it allocates a new thread to each client for processing, after the processing is complete, the thread is destroyed only when the output stream returns a response to the client.
Let's take a look at the code blocking the IO Server:
Server startup
Package COM. bio. demo. server; import Java. io. ioexception; import java.net. serversocket; import java.net. socket; import COM. bio. demo. server. handler. timerserverhandler;/*** @ author zhouxuejun *** @ date 7:08:58 on January 1, October 20, 2014 */public class timeserver {public static serversocket Server = NULL; /*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubtry {Server = new serversocket (8080 ); socket socket = NULL; while (true) {socket = server. accept (); New thread (New timerserverhandler (socket )). start () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
Processing Thread class:
Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. socket;/*** @ author zhouxuejun *** @ date 7:17:28 on January 1, October 20, 2014 */public class timerserverhandler implements runnable {private Socket socket; Public timerserverhandler (Socket socket) {// todo auto-generated constructor Stub this. socket = socket;}/* (non-javadoc) * @ see Java. lang. runnable # Run () */@ overridepublic void run () {// todo auto-generated method stub bufferedreader in = NULL; printwriter out = NULL; try {In = new bufferedreader (New inputstreamreader (this. socket. getinputstream (); out = new printwriter (this. socket. getoutputstream (); string body = NULL; string tag = NULL; while (true) {body = in. readline (); If (null = body) break; out. print (body + "_ return") ;}} catch (ioti Ti On E) {// todo auto-generated catch blockif (null! = In) {try {in. Close ();} catch (ioexception E1) {// todo auto-generated catch blocke1.printstacktrace () ;}} if (null! = Out) {out. Close (); out = NULL;} If (null! = This. socket) {try {This. socket. close ();} catch (ioexception E1) {// todo auto-generated catch blocke1.printstacktrace ();} This. socket = NULL;} e. printstacktrace ();}}}
The code above shows that every time a new client request comes, the server needs to create a new thread to process the new access client request, and one thread can only process one client request. In the high-performance server application field, it is often necessary to provide concurrent access to thousands of clients. Blocking Io obviously cannot meet the needs of high-performance and high-concurrency access scenarios.
Understanding of blocking Io