A TCP Client-Server Program

In the last chapter, we studied TCP theory in detail. Now, we'll look at how we can code up TCP programs in Python.

Introduction

There are a few key points to be noted about TCP programs:

  • TCP connect() calls induce full TCP three-way handshakes! As we saw in the last chapter, three-way handshakes can fail and so can connect() calls.

  • A new socket gets created for every new connection in a TCP architecture.

  • One socket on TCP servers is dedicated to continuously listen for new incoming connections.

  • When a connection is successful, that listening socket creates a new socket exclusively for that connection.

  • When the connection terminates, the associated socket gets deleted.

  • Every socket, and hence each connection, is identified by the unique 4-tuple: (local_ip, local_port, remote_ip, remote_port). All incoming TCP packets are examined to see whether their source and destination addresses belong to any such currently connected sockets.

  • Unlike UDP, TCP segments will be delivered as long as the sender and receiver are connected by a path and they are both live.

  • A sending TCP entity might split TCP segments into packets and so, receiving TCP entities would have to reassemble them. This is unlikely in our small program but happens all the time in the real world. So we need to take care of when there is data leftover in the buffer to send or to receive after one call.

Get hands-on with 1200+ tech skills courses.