About 2119 letters

About 11 minutes

#Python's TCP

Transmission Control Protocol (TCP) is a connection-oriented, reliable transport network communication protocol and one of the core protocols of the modern Internet.

#Client Program

A TCP client program typically just needs to connect to a server and then send and receive data. The following is an example that sends hello\n to the 4242 port of tcpbin.com, which will echo the message back.

import socket # Create a TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Establish connection sock.connect(('tcpbin.com', 4242)) # Send data sock.send('hello\n'.encode()) # Receive data data = sock.recv(1024) print('Received:', data.decode())
  • AF_INET indicates using IPv4 addresses,
  • SOCK_STREAM indicates using TCP
  • The address argument is a tuple, the first element can be a domain name, hostname, or IP address, and the second element is the port number.

#Server Program

A TCP server program needs to bind and listen on an address and port, wait for client connections, and then send and receive data. The following example listens on port 4242 on all IPv4 addresses of the local machine. When it receives a connection from a client, it receives data and echoes it back. Replace tcpbin.com in the client code above with localhost to communicate with this server.

import socket # Create a TCP socket dedicated for listening server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind address and port, 0.0.0.0 means all IPv4 addresses of the local machine server.bind(('0.0.0.0', 4242)) # Listen server.listen(5) # Loop to accept connections while True: sock, addr = server.accept() # Accept connection, create new socket print(f'Received connection from {addr}') data = sock.recv(1024) # Receive data sock.send(data) # Echo back sock.close() # Close connection
  • The argument to listen specifies the size of the connection queue, i.e., the maximum number of connections that can be queued before accept accepts them.

Created in 5/15/2025

Updated in 5/21/2025