Introduction to Socket Programming in Python: TCP and UDP Examples
This article explains the fundamentals of socket programming in Python, covering basic concepts such as IP addresses, ports, and protocols, and provides complete TCP and UDP server/client code examples along with common troubleshooting tips and advanced modules for building robust network applications.
Socket programming is the foundation of network programming, enabling communication between computers. In Python, the built‑in socket module provides an interface to BSD sockets for creating client/server applications.
Basic Concepts
IP address: unique identifier of a device on a network.
Port number: distinguishes services on the same device (0‑65535).
Protocol: communication rules, e.g., TCP (reliable, connection‑oriented) and UDP (unreliable, connection‑less).
Python Socket Module
The socket module allows easy network communication. Below is a minimal TCP socket example:
import socket
# Create a TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket created")Parameters:
AF_INET : use IPv4 addresses.
SOCK_STREAM : use TCP protocol.
Simple TCP Server/Client Implementation
TCP Server Code
import socket
# Create TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind IP and port
server_socket.bind(('127.0.0.1', 12345))
# Listen for connections (max 5 queued)
server_socket.listen(5)
print("Server is listening on port 12345...")
while True:
# Accept client connection
client_socket, addr = server_socket.accept()
print(f"Connection from {addr} established")
# Receive data
data = client_socket.recv(1024)
print(f"Received data: {data.decode()}")
# Send response
client_socket.send("Message received!".encode())
# Close connection
client_socket.close()TCP Client Code
import socket
# Create TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
client_socket.connect(('127.0.0.1', 12345))
# Send data
message = "Hello, Server!"
client_socket.send(message.encode())
# Receive response
response = client_socket.recv(1024)
print(f"Server response: {response.decode()}")
# Close connection
client_socket.close()UDP Server/Client Implementation
UDP Server Code
import socket
# Create UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind IP and port
server_socket.bind(('127.0.0.1', 12345))
print("UDP Server is listening on port 12345...")
while True:
# Receive data
data, addr = server_socket.recvfrom(1024)
print(f"Received from {addr}: {data.decode()}")
# Send response
server_socket.sendto("Message received!".encode(), addr)UDP Client Code
import socket
# Create UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Send data
message = "Hello, UDP Server!"
client_socket.sendto(message.encode(), ('127.0.0.1', 12345))
# Receive response
response, addr = client_socket.recvfrom(1024)
print(f"Server response: {response.decode()}")
# Close socket
client_socket.close()Common Issues and Solutions
Address already in use: use socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) .
Large data transfer: loop to receive until complete or send length prefix.
Timeouts: client_socket.settimeout(10.0) for a 10‑second timeout.
Non‑blocking mode: server_socket.setblocking(False) .
Advanced Socket Programming
socketserver : simplifies server creation.
select : enables I/O multiplexing.
asyncio : supports asynchronous network programming.
Practical Application Scenarios
Chat applications
File transfer tools
Remote control programs
Network games
Distributed system communication
Conclusion
Socket programming is essential for Python network development. This guide covered TCP and UDP socket usage, common pitfalls, and advanced modules, helping developers choose appropriate protocols and patterns for robust network applications.
Beyond implementation, consider security, performance, and reliability; leveraging higher‑level libraries such as requests or aiohttp can further strengthen your solutions.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.