The previous article on how to write a simplest Java socket communication, but in the previous article in the example of a problem is that the server can only accept a client request, when the first client connected to occupy the location, the subsequent client can no longer continue to connect, So you need to make some changes, and when the server does not accept a client connection request, it puts the process into a separate thread to run, and then waits for the next client connection request so that it does not block the server side from receiving the request. Each independently running program closes the socket object after it is finished. The specific code is as follows:
[Java]View Plaincopyprint?
- 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 ();
- }
- }
Here is the client program code:
[Java]View Plaincopyprint?
- 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, run the MyServer class first, then run two myclient classes, then enter the string at each myclient prompt, and you can see that the server can receive requests to process each client individually.
Implementing multithreaded Sokect