Lesson 21: TCP Sockets — Server and Client
TCP (Transmission Control Protocol) is the foundation of every reliable network communication. When you open a browser, run a Git fetch, or connect two NCCL processes for distributed training — in most cases TCP is working behind the scenes. In this lesson we will write a TCP server and TCP client i
Think of a TCP server as a restaurant. First you pick a table number (bind to a port), then you open the door and announce 'we are open' (listen), then you sit and wait for a customer to walk in (accept). The customer arrives (connect), sits down, orders (send), and gets the order echoed back (recv). TCP guarantees every dish arrives in the right order and nothing is missing — like a waiter who checks each plate arrived before serving the next.
- socket
- An endpoint for network communication. Represented in code as a file descriptor (integer) that you can write to and read from just like a file.
- bind
- Assigning an IP address and port to a socket. The bind() syscall tells the kernel: 'this socket will receive connections arriving on port X'.
- listen
- Switching the socket into passive mode so it is ready to accept incoming connections. The backlog parameter sets how many pending connections the kernel can hold in its queue.
- accept
- Pulling the next connection from the waiting queue. Returns a new dedicated file descriptor for that single client. The original socket keeps listening for more clients.
- SO_REUSEADDR
- A socket option that lets you rebind the port immediately after the server closes, without waiting for TIME_WAIT to expire. Essential during development to avoid 'Address already in use' on every restart.