Java TCP Socket programming and javatcpsocket Programming
1. Implementation of TCP Socket in Java
Java provides two classes for TCP: Socket and ServerSocket. A Socket instance represents one end of a TCP connection. A TCP connection is an abstract two-way channel. The two ends are determined by the IP address and port number respectively. Before communication starts, a TCP connection needs to be established. The client TCP needs to send a connection request to the server TCP. The ServerSocket instance listens to TCP connection requests and creates a new Socket instance for each request. That is to say, the server must process both the ServerSocket instance and the Socket instance, while the client only needs to use the Socket instance. Each Socket instance is associated with an InputStream and OutputStream object. We write bytes into the Socket's OutputStream to send data and receive data from InputStream.
2. TCP connection establishment steps
After the client sends a connection request to the server, it passively waits for the server's response. The typical TCP client must go through the following three steps:
1. Create a Socket instance: the constructor establishes a TCP connection to the specified remote host and port;
2. Communicate with the server through the socket I/O stream;
3. Use the close method of the Socket class to close the connection.
The server establishes a communication terminal and passively waits for the client connection. A typical TCP server performs the following two steps:
1. Create a ServerSocket instance and specify a local port to listen to TCP connection requests sent by the client on this port;
2. Repeated execution:
1) Call the ServerSocket accept () method to obtain the client connection and create a Socket instance through its return value;
2) Enable a new thread for the returned Socket instance and use the I/O Stream of the returned Socket instance to communicate with the client;
3) after the communication is complete, use the close () method of the Socket class to close the Socket connection of the client.