Building Java Client/Server Applications with TCP
Abstract: TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers. It also provides a point-to-point channel for applications that require reliable communications. The Java programming language supports, through the java.net package, a suitable API for developing client/server applications that use this protocol for communication.
1.The principles of the TCP protocol
The TCP protocol requires the establishment of a session between the client and the server. A session essentially is a mechanism to get some data, so we are setting up a specialized communication session.
TCP behaves so similarly to a conversation on the phone.
- Pick up the phone
- Wait for the dial tone
- Dial the number
- Phone rings
- Pick up the phone
- Say hello
- Start the conversation
- Repeat if you haven't understood something
A three-way handshake (or TCP handshake) is a method used in a TCP/IP network to create a connection between a local host/client and server. It is a three-step method that requires both the client and server to exchange SYN and ACK (acknowledgment) packets before actual data communication begins.
This is how the TCP 3-way handshake works:
- A client node sends a SYN data packet over an IP network to a server on the same or an external network. The objective of this packet is to ask/infer if the server is open for new connections.
- The target server must have open ports that can accept and initiate new connections. When the server receives the SYN packet from the client node, it responds and returns a confirmation receipt – the ACK packet or SYN/ACK packet.
- The client node receives the SYN/ACK from the server and responds with an ACK packet.
The four-way disconnect is the method used in a TCP/IP network to close the connection between a client and a server.
This is how the TCP 4-way disconnect works:
- The client sends a FIN packet to the server and updates its state to FIN_WAIT_1
- The server receives the termination request from the client, responds with ACK and moves to CLOSE_WAIT
- The client receives the reply from the server and will go to FIN_WAIT_2
- The server is in CLOSE_WAIT and will follow up with FIN, which updates the state to LAST_ACK
- The client receives the termination request and replies with an ACK, which results in a TIME_WAIT state
- The server is finished and sets connection to CLOSED
- The client stays in TIME_WAIT for a maximum of 4 minutes before setting the connection to CLOSED