What is TCP and how does it work?
Internet Protocol, or IP, provides an unreliable packet delivery system--each packet is an individual, and is handled separately. Packets can arrive out of order or not at all. The recipient does not acknowledge them, so the sender does not know that the transmission was successful. There are no provisions for flow control--packets can be received faster than they can be used. And packet size is limited.
Transmission Control Protocol (TCP) is a network protocol designed to address these problems. TCP uses IP, but adds a layer of control on top. TCP packets are lost occasionally, just like IP packets. The difference is that the TCP protocol takes care of requesting retransmits to ensure that all packets reach their destination, and tracks packet sequence numbers to be sure that they are delivered in the correct order. While IP packets are independent, with TCP we can use streams along with the standard Java file I/O mechanism.
There are four distinct elements that make a TCP connection unique:
- IP address of the server
- IP address of the client
- Port number of the server
- Port number of the client
Each requested client socket is assigned a unique port number while the server port number is always the same. If any of these numbers is different, the socket is different. A server can thus listen to one and only one port, and talk to multiple clients at the same time.
So a TCP connection is somewhat like a telephone connection; you need to know not only the phone number (IP address), but because the phone may be shared by many people at that location, you also need the name or extension of the user you want to talk to at the other end (port number). The analogy can be taken a little further. If you don't hear what the other person has said, a simple request ("What?") will prompt the other end to resend or repeat the phrase, and the connection remains open until someone hangs up.