HOWTO · Python

Socket Programming in Python: A Beginners Guide

Learn Python socket programming by building local TCP and UDP clients and servers, then compare how the protocols deliver data.

On this page

Python socket programming lets two processes exchange data through communication endpoints called sockets. This guide uses the standard-library socket module to build local TCP and UDP client/server exchanges, and explains when each protocol is useful. No package installation is needed.

Socket Programming in Python: Overview and Setup

A server waits for a client; a client initiates communication with the server. In these examples both run on one computer, using 127.0.0.1 and the same port. The socket.socket() constructor creates a socket. Choose socket.SOCK_STREAM for TCP or socket.SOCK_DGRAM for UDP. Text must be encoded to bytes before sending and decoded after receiving.

Run each complete code block below once in a single terminal. Each script starts its server in a background thread, then the same script acts as the client to exchange one message over the loopback interface and close its sockets.

Build a TCP Server and Client

TCP uses a connection-oriented, reliable, ordered byte stream. The server binds to an address and port, calls listen(), and waits in accept(). The client connects to that same address and port. Once connected, both sides can send and receive bytes. sendall() sends all bytes in the supplied buffer, while recv(1024) reads up to 1,024 bytes. A TCP read does not mark application message boundaries, so a larger protocol needs its own framing, such as a length prefix or delimiter.

Run this example:

import socket
import threading

HOST = "127.0.0.1"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
    probe.bind((HOST, 0))
    PORT = probe.getsockname()[1]
ready = threading.Event()


def serve():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind((HOST, PORT))
        server.listen(1)
        ready.set()
        connection, _ = server.accept()
        with connection:
            message = connection.recv(1024).decode("utf-8")
            connection.sendall(("Received: " + message).encode("utf-8"))


thread = threading.Thread(target=serve)
thread.start()
ready.wait()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
    client.connect((HOST, PORT))
    client.sendall(b"Hello over TCP")
    reply = client.recv(1024).decode("utf-8")
thread.join()
print(reply)

The operating system assigns an available local port so the example can run without a fixed port conflict. The thread lets the server accept while the client connects; each socket is closed by its context manager after the exchange.

Build a UDP Server and Client

UDP sends independent datagrams without creating a TCP-style connection. The server binds to an address and waits with recvfrom(), which returns both the received bytes and the sender’s address. The client uses sendto() with the server address, then recvfrom() to receive the reply and its sender address. The following local example uses the same loopback address and lets the operating system select the server port.

Run this example:

import socket
import threading

HOST = "127.0.0.1"
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
    probe.bind((HOST, 0))
    PORT = probe.getsockname()[1]
ready = threading.Event()


def serve():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
        server.bind((HOST, PORT))
        ready.set()
        message, client_address = server.recvfrom(1024)
        reply = ("Received: " + message.decode("utf-8")).encode("utf-8")
        server.sendto(reply, client_address)


thread = threading.Thread(target=serve)
thread.start()
ready.wait()
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
    client.sendto(b"Hello over UDP", (HOST, PORT))
    reply, server_address = client.recvfrom(1024)
thread.join()
print(reply.decode("utf-8"))

A datagram is delivered to a destination address and port, but UDP does not guarantee that it arrives or that multiple datagrams arrive in order. The example decodes the message bytes before building the response, so the reply contains readable text rather than a Python bytes representation.

Choose Between TCP and UDP

Choose TCP when the application needs an ordered byte stream and the transport’s delivery and retransmission behavior. Applications still need to handle connection failures and define message framing; TCP does not guarantee that a peer application processes a message. Choose UDP when independent datagrams suit the task and the application can tolerate loss or reordering, or can handle those conditions itself. UDP is not inherently faster: performance depends on the network, workload, and reliability features the application needs. Broadcasting is possible with UDP when socket and network settings permit it, but it is not a general substitute for a reliable client/server exchange.

Conclusion

The socket module provides the building blocks for both protocols. TCP examples use SOCK_STREAM, accept(), sendall(), and recv() to exchange data over a connection; UDP examples use SOCK_DGRAM, sendto(), and recvfrom() to exchange addressed datagrams. Start with a local client and server, then choose TCP or UDP according to the delivery behavior your application requires.