In Java Network programming Note 4, we saw the process of client-server communication, just an example of a single client-to-server communication in the previous program.
Next we see how to implement multiple client and server communication, for the server, it to each client request for a socket to establish a thread, and through it to communicate.
Here you create a thread class to manage the socket:
<span style= "FONT-SIZE:18PX;" >public class Serverthread extends Thread {private socket socket;private int num;public serverthread (Socket socket,int num) {this.socket=socket;this.num=num;} @Overridepublic void Run () {try {InputStream is=socket.getinputstream (); OutputStream Os=socket.getoutputstream ();D Atainputstream dis=new DataInputStream (IS); String Request=dis.readline (); SYSTEM.OUT.PRINTLN (Request); PrintStream ps=new printstream (OS);p S.print ("This is----from the server >"); Socket.close ();} catch (Exception e) {e.printstacktrace ();}}} </span>
Then run the main program to communicate with the client:
<span style= "FONT-SIZE:18PX;" >public class Server {public static void main (string[] args) {try {serversocket ss=new serversocket (+); int Clientnum =0;while (True) {Serverthread st=new serverthread (ss.accept (), clientnum); St.start (); System.out.println (clientnum++);}} catch (Exception e) {e.printstacktrace ();}}} </span>
There is no difference between the client and the previous:
<span style= "FONT-SIZE:18PX;" >public class Client {public static void main (string[] args) {try {socket socket = new Socket ("192.168.12.112", +); B Ufferedreader bfr = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); String Request=bfr.readline (); SYSTEM.OUT.PRINTLN (request); OutputStream OutputStream = Socket.getoutputstream (); PrintStream PrintStream = new PrintStream (outputstream);p rintstream.print ("Client--->"); Socket.close ();} catch (Unknownhostexception e) {//Todo auto-generated catch Blocke.printstacktrace ()} catch (IOException e) {//Todo Aut O-generated catch Blocke.printstacktrace ();}}} </span>
Reprint Please specify source:http://blog.csdn.net/hai_qing_xu_kong/article/details/42803955 Emotional Control _
Java Network Programming Note 5