Address: http://blog.csdn.net/kongxx/article/details/7259465
One of Java Socket practices: Single-thread Communication
PreviousArticleSpeaking of how to write a simplest Java Socket communication, but one problem in the previous article is that the server can only accept one client request, which occupies this position after the first client connection, later, the client cannot continue to connect, so some changes need to be made. When the server is not received a client connection request, the processing process is put into an independent thread to run, then wait for the next client connection request, so that the server will not block the server from receiving the request. EachProgramClose the socket object after it is used. DetailsCodeAs follows:
Package COM. googlecode. garbagecan. test. socket. sample2; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. serversocket; import java.net. socket; public class myserver {public static void main (string [] ARGs) throws ioexception {serversocket Server = new serversocket (10000); While (true) {Socket socket = server. accept (); invoke (socket) ;}} Private Static void invoke (final Socket Client) throws ioexception {New thread (New runnable () {public void run () {bufferedreader in = NULL; printwriter out = NULL; try {In = new bufferedreader (New inputstreamreader (client. getinputstream (); out = new printwriter (client. getoutputstream (); While (true) {string MSG = in. readline (); system. out. println (MSG); out. println ("server received" + MSG); out. flush (); If (MSG. equals ("bye") {break ;}} catch (ioexception ex) {ex. printstacktrace ();} finally {try {In. close ();} catch (exception e) {} Try {out. close () ;}catch (exception e) {}try {client. close () ;}catch (exception e ){}}}}). start ();}}
The following is the client code:
Package COM. googlecode. garbagecan. test. socket. sample2; import Java. io. bufferedreader; import Java. io. inputstreamreader; import Java. io. printwriter; import java.net. socket; public class myclient {public static void main (string [] ARGs) throws exception {Socket socket = new socket ("localhost", 10000 ); bufferedreader in = new bufferedreader (New inputstreamreader (socket. getinputstream (); printwriter out = new printwriter (socket. getoutputstream (); bufferedreader reader = new bufferedreader (New inputstreamreader (system. in); While (true) {string MSG = reader. readline (); out. println (MSG); out. flush (); If (MSG. equals ("bye") {break;} system. out. println (in. readline ();} socket. close ();}}
Test: first run the myserver class, then run two myclient classes, and then enter a string at each myclient prompt. Then, the server can receive and process requests from each client.