TCP-based socket communication:
Server-side:
- Create a server-side socket, that is, ServerSocket, specify the bound port, and listen for this port
- Call the Accept () method to start listening, waiting for the client to connect
- After the connection is established, read the request information sent by the customer through the input stream
- Send response information to the client via output flow
- Close related Resources
Client:
- Create a client socket, specify the server address and port
- After the connection is established, the message is sent to the server through the output stream
- Gets the input stream and reads the server-side response information
- Close Resource
Example: Server side:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServer { Public Static voidMain (string[] args) {Try { //1. Create a server-side socket, which is serversocket, specify the bound port and listen for this portServerSocket serversocket=NewServerSocket (8888); Socket Socket=NULL; //log the number of clients intCount=0; System.out.println ("* * * server is about to start, waiting for client connections * * *"); //loop monitoring waits for a client's connection while(true){ //call the Accept () method to start listening, waiting for the client to connectsocket=serversocket.accept (); //Create a new threadServerthread serverthread=Newserverthread (socket); //Start ThreadServerthread.start (); Count++;//Count the number of clientsSystem.out.println ("Number of clients:" +count); InetAddress Address=socket.getinetaddress (); System.out.println ("IP for current client:" +address.gethostaddress ()); } } Catch(IOException e) {e.printstacktrace (); } }}
Client:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.net.UnknownHostException; Public classClient { Public Static voidMain (string[] args) {Try { //1. Create a client socket, specify the server address and PortSocket socket=NewSocket ("localhost", 8888); //2. Get the output stream and send the message to the server sideOutputStream Os=socket.getoutputstream ();//byte output streamPrintWriter pw=NewPrintWriter (OS);//wrapping the output stream as a print streamPw.write ("User name: Alice; Password: 789"); Pw.flush (); Socket.shutdownoutput ();//turn off the output stream//3. Get the input stream and read the server-side response informationInputStream is=Socket.getinputstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (IS)); String Info=NULL; while((Info=br.readline ())! =NULL) {System.out.println ("I am the client, the server says:" +info); } //4. Close ResourcesBr.close (); Is.close (); Pw.close (); Os.close (); Socket.close (); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }}
Server Thread processing classes:
ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public classServerthreadextendsThread {//socket associated with this threadSocket socket =NULL; PublicServerthread (socket socket) { This. Socket =socket; } //A thread performs an action that responds to a client's request Public voidrun () {InputStream is=NULL; InputStreamReader ISR=NULL; BufferedReader BR=NULL; OutputStream OS=NULL; PrintWriter PW=NULL; Try { //gets the input stream and reads the client informationis =Socket.getinputstream (); ISR=NewInputStreamReader (IS); BR=NewBufferedReader (ISR); String Info=NULL; while((Info=br.readline ())! =NULL){//iterating through the client's informationSystem.out.println ("I am the server, the client says:" +info); } socket.shutdowninput ();//close the input stream//gets the output stream that responds to the client's requestOS =Socket.getoutputstream (); PW=Newprintwriter (OS); Pw.write ("Welcome you!" "); Pw.flush ();//Call the Flush () method to buffer the output}Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{ //Close Resource Try { if(pw!=NULL) Pw.close (); if(os!=NULL) Os.close (); if(br!=NULL) Br.close (); if(isr!=NULL) Isr.close (); if(is!=NULL) Is.close (); if(socket!=NULL) Socket.close (); } Catch(IOException e) {e.printstacktrace (); } } }}
To transfer objects using TCP traffic:
ObjectOutputStream oos=new objectoutputstream (OS);
User User=new User ("admin", "123");//Package As Object
Oos.writeobject (user);//serialization
Tips:
Priority issue: Serverthread.setpriority ();//lower priority to prevent slow running
Input and output stream problem: the same socket, close the output stream will close the associated socket, so do not close the output stream, and finally close the socket.
TCP for Java socket programming