π 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
socket
module 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 :