This example shows a multi-user/server communication model with three files: Server.java Serverthread.java and Client.java classes. Where the Serverthread class supports multi-threading, all operations provided to the customer are encapsulated in the class, and the constructor of the class Serverthread (socket socket) receives a socket object for data communication with the customer. The server class is an application whose main method waits and listens for multiple user connection requests (in this case, only one customer request) through an infinite Whlie loop, and each client's connection is handled by a separate thread on the server side, which enables communication between multiple users/servers.
The code for the server class is as follows:
Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** The server class receives the client's socket request and then creates a serverthread thread to process the request *@authorAdministration **/ Public classServer { Public Static voidMain (string[] args) {System.out.println ("Waiting for connection ... "); Try { //1. Create a Socket object ServerSocket, set the port number to 6666ServerSocket ServerSocket =NewServerSocket (6666); Socket Clientsocket=NULL; //2. Listen for socket response, once the corresponding, create a new Serverhread class to handle this response while(true) {Clientsocket= Serversocket.accept ();//Monitor NewServerthread (Clientsocket); } } Catch(IOException e) {e.printstacktrace (); } }}
The code for the Serverthread class is as follows:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public classServerthreadextendsThread {//Client by Socket PrivateSocket Clientsocket =NULL; //Client Input Stream PrivateInputStream Clientinput =NULL; //Client output Stream PrivateOutputStream Clientoutput =NULL; //1. First obtain the client socket request from the constructor method, create a stream to input and output to the client, and start the thread to execute the next request PublicServerthread (Socket socket)throwsIOException {clientsocket=socket; Clientinput=Clientsocket.getinputstream (); Clientoutput=Clientsocket.getoutputstream (); This. Start (); } //2. After the thread is started, the data from the client is retrieved and analyzed by buffering the stream, and if "over" is passed, the thread is terminated and the port is closed;//Conversely, the calculated value passed from the client corresponds to the area of the square side length, and returns the result back to the client, then closes the port . Public voidrun () {Try { //build a buffered input stream to get the data sent by the clientBufferedReader Bufreader =NewBufferedReader (NewInputStreamReader (clientinput)); //read input stream content (data) by rowString StrLine =Bufreader.readline (); //Judging input stream data if("Over". Equalsignorecase (StrLine)) { //creates an output stream, passing "over" information, indicating the end of the connectionPrintWriter PrintWriter =NewPrintWriter (Clientoutput,true); Printwriter.println ("Connect Over"); }Else { //input square side length, and output edge length and area DoubleSide =double.parsedouble (StrLine); Side=double.parsedouble (StrLine); System.out.println ("Side of Square Received:" +side); DoubleSquarearea = side*side; String Str= "Side:" +side+ "Square:" +Squarearea; //create output flow to client pass operation resultsPrintWriter PrintWriter =NewPrintWriter (Clientoutput,true); Printwriter.println (str); System.out.println ("Finish Sending to client!"); } } Catch(IOException e) {e.printstacktrace (); }finally { //close the stream and port Try{clientinput.close (); Clientoutput.close (); Clientsocket.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
The client class code is as follows:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException;ImportJava.util.Scanner;/*** Client class *@authorAdministration **/ Public classClient { Public Static voidMain (string[] args) {socket socket=NULL; Try { //1. Create a connection to the server side based on the port numberSocket =NewSocket ("127.0.0.1", 6666); //2. The client obtains the information that the user entered in the console//get the value of keyboard input via scannerSystem.out.println ("Input Side:"); Scanner Keyinput=NewScanner (system.in); //read keyboard input by lineString StrLine =Keyinput.nextline (); //3. Create the client's input stream and output stream, send the user input to the server side, and then receive the results from the server side of the Operation//get server input streamOutputStream OutputStream =Socket.getoutputstream (); //get server output streamInputStream InputStream =Socket.getinputstream (); //sending data to the server via PrintWriter outputPrintWriter PrintWriter =NewPrintWriter (OutputStream,true); Printwriter.println (StrLine); BufferedReader Bufdreader=NewBufferedReader (NewInputStreamReader (InputStream)); System.out.println (Bufdreader.readline ()); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally { Try { //4. Closing Sockets and StreamsSocket.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
Server-side operation results:
Wait for connection ... Side of Square Received:5.0Finish sending to client!
The results of the client run:
Input Side:5Side:5.0 square:25.0
Java Network Programming Learning--Constructing the network communication model based on multithreading 1