Detailed communication based on TCP Socket

Socket communication is a transport layer communication protocol based on TCP, the communication is between an application and the application, typically in the chat application.

establish connection

Create a connection needs to use the socket socket client and server using Socket.

Linux memory to create a Socket, socket just created with some differences.

public class EchoServer{
         private int port;
         Socket socket;
         public EchoServer(int port){
             this.port = port;  

        }  
       
         private void run() throws IOException{
            
             ServerSocket serverSocket = new ServerSocket(7890);
             while(true){
                socket = serverSocket.accept();
                new Thread(()->{
                    write(socket);
                }).start();

             }
            
             

        }

        private void write(Socket socket){
             InputStream in =  new InputStream(socket);  
             OutputStream out = new OutputStream();
             int n ;
             byte[]  b = new byte[1024];
             while((n=in.read(b))>0){
                   out.write(b,0,b.length);
             } 
        }

}                                         

  

public class EchoClient{
     private Socket socket;
    
     private void write(socket){
          InputStream in = new InputStream(socket);
          OutputStream out = new OutputStream();
          int n ;
          byte[] b = new byte[1024];
          while((n=in.read(b))>0){
             System.out.write(b,0,b.length);
         }
     }


     public void static main(String[] args){
           Socket socket = new Socket("localhost",7890);
           
           write(socket);           
     }
    
}

  

 

Socket is one kind of usefulness monitor, called ServerSocket, Socket calls this method listen, and listening socket on the connection.

Another use is to connect the socket, it calls the connect method, role and client communications services connecting sleeve words.

 

A complete TCP communications, create a total of three socket on the server and the client.

A monitoring of the socket in the server monitoring client socket connection is successful, and produces a connection after receiving the connection socket of.

A connector socket in the client request to initiate connection.

 

 

Guess you like

Origin www.cnblogs.com/gzhich2019/p/11899128.html