Python Networking with Socket – TCP, UDP, and Client-Server
Introduction – Why Learn Networking in Python?
Networking allows programs to communicate across systems, enabling technologies like web browsers, APIs, and multiplayer games. Python’s built-in socket module makes it easy to:
- Create TCP and UDP connections
- Build client-server applications
- Transfer data over local or internet connections
Whether you’re developing chat apps, IoT services, or REST APIs, understanding networking in Python is essential for backend and system-level development.
In this guide, you’ll learn:
- How Python networking works
- Client-server architecture with
socket - TCP vs UDP communication
- Real-world networking examples
- Best practices and FAQs
What Is Networking in Python?
Networking refers to communication between multiple devices using protocols like TCP/IP or UDP.
Python provides the socket module to work with low-level network connections.
Python’s socket Module Overview
To use networking in Python:
import socket
Key functions:
| Function | Purpose |
|---|---|
socket() | Create a new socket object |
bind() | Bind server to a host/port |
listen() | Listen for incoming connections |
accept() | Accept a connection |
connect() | Connect to a remote socket |
send() / recv() | Send and receive data |
close() | Close the connection |
TCP Client-Server Example (Socket Programming)
Server Code:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 9999))
server.listen()
print("Server is listening...")
client_socket, addr = server.accept()
print(f"Connected to {addr}")
data = client_socket.recv(1024).decode()
print("Received:", data)
client_socket.send("Message received!".encode())
client_socket.close()
server.close()
Client Code:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 9999))
client.send("Hello Server".encode())
response = client.recv(1024).decode()
print("Server Response:", response)
client.close()
Output:
Server is listening...
Connected to ('127.0.0.1', 54321)
Received: Hello Server
Server Response: Message received!
UDP Client-Server Example
UDP Server:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 9999))
print("UDP server listening...")
data, addr = server.recvfrom(1024)
print("Received:", data.decode())
server.sendto("ACK".encode(), addr)
UDP Client:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("Ping".encode(), ('localhost', 9999))
data, _ = client.recvfrom(1024)
print("Server:", data.decode())
TCP vs UDP Comparison
| Feature | TCP | UDP |
|---|---|---|
| Protocol Type | Connection-oriented | Connectionless |
| Reliability | High (guaranteed delivery) | Low (no guarantee) |
| Speed | Slower | Faster |
| Use Case | Web, FTP, Email, File transfer | Video, Audio, DNS, Games |
Network Programming Tips
| Do This | Avoid This |
|---|---|
| Use try-except to handle socket errors | Letting your app crash on disconnect |
Always close sockets with close() | Leaving sockets open |
| Use threads for multiple clients | Blocking the server with one client |
Set timeouts with settimeout() | Hanging indefinitely on receive |
Real-World Use Cases of Python Networking
- Chat Applications – Peer-to-peer or server-based
- IoT Devices – Python-based sensors and Raspberry Pi
- Web Servers – Basic HTTP services or frameworks
- Remote Monitoring – Collect metrics from remote systems
- Socket APIs – Used in frameworks like Flask, Django Channels
Summary – Recap & Next Steps
Python networking gives you low-level control over socket communication. You can build reliable client-server systems with just a few lines of code.
Key Takeaways:
- Use the
socketmodule for TCP/UDP communication - Understand the differences between
connect(),bind(), andlisten() - Handle errors and close connections properly
- Use threads for concurrent client handling in servers
Real-World Relevance:
Used in chat apps, device communication, socket APIs, and low-level services.
FAQ – Python Networking Basics
What is the difference between TCP and UDP?
TCP is reliable and connection-based, UDP is faster but connectionless.
How do I send data between two Python programs?
Use the socket module with matching client-server ports and IP addresses.
Is the socket module built-in?
Yes. It’s included in Python’s standard library—no installation needed.
How do I handle multiple clients on a TCP server?
Use threading or asyncio to handle each client in a separate thread or coroutine.
Can I use networking in Python for local communication?
Yes. Use localhost or 127.0.0.1 for loopback (local-only) connections.
Share Now :
