This article address: http://blog.csdn.net/kongxx/article/details/7259465
Java socket Combat one single-threaded communication
The previous article talked about how to write a simplest Java socket communication, but the example in the previous article had the problem that the server could only accept a client request, and that after the first client connected it, the subsequent client could not continue to connect, So, when the server does not receive a client connection request, it puts the processing process into a separate thread to run, then waits for the next client connection request, so that the server side is not blocked from receiving requests. Each independently running program closes the socket object after it has finished using it. The specific code is as 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 SERVERSOC
KET (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 program 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 ("Loca Lhost ", 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, run the MyServer class first, then run two myclient classes, then enter a string at each myclient prompt, and you can see that the server can receive each client request separately.