To undertake the previous article, today talk about the ability to multi-client link serversocket.
Note that the technical points involved are:
1.ServerSocket
2. Multithreading
This time we are divided into two classes to implement, first on the code:
package com.test.socket;import java.io.ioexception;import Java.io.InputStream; Import Java.io.outputstream;import java.io.printwriter;import Java.net.socket;import Java.util.Scanner;public class Threadedechohandler implements Runnable {private socket socket = Null;public Threadedechohandler (socket s) {This.socket = s;} @Overridepublic void Run () {InputStream inputstream;try {inputstream = Socket.getinputstream (); outputstream OutputStream = Socket.getoutputstream (); Scanner Scanner = new Scanner (InputStream); PrintWriter printwriter = new PrintWriter (OutputStream, True);p rintwriter.println ("Welcome to TestServer"); Boolean Done = False;while (!done && scanner.hasnextline ()) {String line = Scanner.nextline ();p rintwriter.println ("Echo : "+ Line", if (Line.trim (). Equals ("Bye")) {done = true;}}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
The main function of the Threadedechohandler class is almost identical to that of the previous article. is to accept the data sent by the client, and then copy the print out, but here is inherited runnable, can support multi-threading
Package Com.test.socket;import Java.io.ioexception;import Java.io.inputstream;import java.io.outputstream;import Java.io.printwriter;import Java.net.serversocket;import Java.net.socket;import Java.util.Scanner;public class testsocket {public static void main (string[] args) throws IOException {ServerSocket serversocket = new ServerSocket (8189); while (true) {Socket socket = serversocket.accept (); Threadedechohandler handler = new Threadedechohandler (socket); Thread thread = new thread (handler); Thread.Start ();}}}
Testsocket is still a test class, where there is a difference from the previous article in the while loop inside, every client link, he will open a separate thread service
To expand, the test class here is only used for testing, assuming that the performance of the problem, this is usually taken to take the thread pool, and also need to check whether the link is still in the detection class, or the addition of the client link, the memory directly exploded.
And there's something missing in these two classes, such as how the client exits? Check links? Half closed? Wait, these are to be continued later.
Getting Started with Java Basics-building a serversocket that can be multi-client linked