Learn how to write TCP servers using Python's socket module
TCP is a widely used network protocol. It's the underlying protocol for HTTP, SSH and many other protocols that you're probably familiar with.
In this concept we'll learn how to write a TCP server in Python using the socket module.
Not familiar with TCP? Try the "TCP: An Overview" concept first.
TCP is a widely used network protocol. It's the underlying protocol for HTTP, SSH and many other protocols that you're probably familiar with.
In this concept we'll learn how to write a TCP server in Python using the socket module.
Not familiar with TCP? Try the "TCP: An Overview" concept first.
socket modulePython's socket module provides access to networking primitives.
To write TCP servers in Python, you'll need to be familiar with the following methods:
socket.create_connectionsocket.create_serversocket.Socket.acceptsocket.Socket.recvsocket.Socket.sendallWe'll start by looking at socket.create_connection and socket.create_server
socket.create_connection is used to initiate outbound connections.
Example usage:
# Connects to a TCP server running on localhost:8080 and returns the associated socket
client_socket = socket.create_connection(("localhost", 8080))
socket.create_server is used to create TCP servers to accept inbound connections.
Example usage:
# Starts a TCP server listening on localhost:8080 and returns the associated socket
server_socket = socket.create_server(("localhost", 8080))
socket.create_server methodThis is the interface for socket.create_server:
def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False)
To create a TCP server, you'd pass in a tuple consisting of (host, port) like ("localhost", 8080) as address.
# Starts a TCP server listening on localhost:8080
server_socket = socket.create_server(("localhost", 8080))
Once a server is created using socket.create_server, the socket.Socket.accept method can be used to accept incoming connections.
The socket.Socket.accept method blocks execution and waits for an incoming connection.
connection, address = server_socket.accept()
When a client connects, it returns a new Socket object representing the connection and a tuple holding the address of the client.
This socket object can be used to read and write data to the connection.
The following methods are used to read and write data to the connection.
socket.Socket.recv reads data from a connection. The maximum amount of data to be received at once is specified by bufsize:
def recv(bufsize[, flags])
It returns a bytes object with the received data. If an empty bytes object is received, it signals that the client closed the connection.
connection, address = server_socket.accept()
data = connection.recv(1024)
socket.Socket.sendall writes data to a connection.
def sendall(bytes[, flags])
The data to be written needs to be passed in as a bytes object.
connection.sendall(b"Hello, client!")
Using socket.Socket.sendall is often easier than using socket.Socket.send since it automatically handles the case where the entire buffer isn't written to the connection in one go.
Now that you're familiar with the various socket methods in socket, let's see how to put them all together to create a simple TCP server that echos a string:
# Start a TCP server on localhost:8080
with socket.create_server(("localhost", 8080), reuse_port=true) as server_socket:
# Block until we receive an incoming connection
connection, address = server_socket.accept()
print(f"accepted connection from {address}")
# Read data
data = connection.recv(1024)
# Write the same data back
connection.sendall(data)
You've now learnt about how to use functions in the socket module to build a TCP server.
A quick recap of the functions we've covered:
socket.create_connection: Connects to a TCP server.socket.create_server: Starts a TCP server that listens for incoming connections.socket.Socket.accept: Accepts an incoming connection.socket.Socket.recv: Receives data from a connection.socket.Socket.sendall: Writes data to a connection. The full documentation for the socket module can be found here.