What Are Sockets in Python and How Do They Work
A socket is a software interface that enables two-way communication between nodes in a computer network. Think of it as a virtual plug through which applications can send and receive data over a network.
Modern network applications heavily rely on Python sockets to build various systems. From messaging apps to online games and data exchange services — network communication through sockets is everywhere.
Key Concepts in Network Programming
To work with sockets in Python, you need to understand these core concepts:
- IP Address — a unique address identifying a device on the network
- Port — a numeric identifier for a service running on a device
- TCP (Transmission Control Protocol) — a reliable data transfer protocol
- UDP (User Datagram Protocol) — a fast protocol without delivery confirmation
TCP guarantees reliable data delivery with error checking. UDP is faster but does not guarantee message delivery.
Setting Up and Importing the Socket Library
The socket module is part of Python's standard library. To start working with sockets, simply import it:
import socket
No additional installations are needed. The socket library is available in all Python versions by default.
Creating a TCP Server in Python
Basic Server Implementation
A TCP server accepts connections from clients and processes their requests. Here's a simple implementation:
import socket
# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind to address and port
server_socket.bind(('localhost', 12345))
# Start listening (max 5 connections in queue)
server_socket.listen(5)
print("Server started. Waiting for connections...")
while True:
# Accept a connection
client_socket, address = server_socket.accept()
print(f"Connection from {address}")
# Receive a message
message = client_socket.recv(1024).decode('utf-8')
print(f"Received message: {message}")
# Send a response
client_socket.send("Hello from server!".encode('utf-8'))
# Close the client connection
client_socket.close()
Understanding How the Server Works
Here's what happens in the code above:
- A socket is created using the TCP protocol
- The server binds to the localhost address and port 12345
- It starts listening for incoming client connections
- When a client connects, the server receives its message
- The server sends a response and closes the connection
The socket.AF_INET method specifies IPv4, while socket.SOCK_STREAM specifies the TCP protocol.
Building a TCP Client
A TCP client connects to a server and exchanges data with it. Here's an example client implementation:
import socket
# Create a client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server
client_socket.connect(('localhost', 12345))
# Send a message
client_socket.send("Hello, server!".encode('utf-8'))
# Receive a response
response = client_socket.recv(1024).decode('utf-8')
print(f"Server response: {response}")
# Close the connection
client_socket.close()
The client follows a sequence of steps: connect, send data, receive a response, and close the connection.
Working with the UDP Protocol
UDP provides a faster way to transfer data without delivery guarantees. This makes it suitable for real-time applications.
UDP Server
Blogs
Functional Programming in C++: Advanced Level
Regular Expressions in PHP with Examples: A Complete Guide for Beginners
Python Developer Interview: How to Ace Your Coding Interview
Book Recommendations
Read also
Clean Code in C++: Principles of Writing Readable Code
PHP in 2025: What's New in Practice — Overview of Innovations
TypeScript error TS2533: how to remove it and what's under the hood
Kotlin Libraries That Will Save Your Project in 2024
Architectural Patterns in C++: How to Write Code You Won't Be Ashamed to Show