Python - Socket Programming
Socket programming is the foundation of network communication in Python. It allows two devices (or programs) to communicate with each other over a network using protocols like TCP or UDP.
With socket programming, you can build:
- Chat applications
- Web servers
- File transfer tools
- Multiplayer games
- Network-based services
In this tutorial, you will learn socket programming in Python with clear examples and real-world understanding.
What is Socket Programming?
Socket programming is:
A method of enabling communication between two machines using sockets as endpoints.
A socket acts like a communication channel between a client and a server.
What is a Socket?
A socket is:
An endpoint that sends and receives data over a network.
Each socket has:
- IP address
- Port number
Types of Sockets
1. Stream Socket (TCP)
- Reliable communication
- Connection-based
- Ensures data delivery
2. Datagram Socket (UDP)
- Fast communication
- Connectionless
- No guarantee of delivery
Python Socket Module
Python provides socket programming using:
import socketTCP Socket Programming (Client-Server Model)
Server Side
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("localhost", 9090))
server.listen(1)
print("Server is waiting...")
conn, addr = server.accept()
print("Connected with", addr)
data = conn.recv(1024).decode()
print("Client:", data)
conn.send("Hello from server".encode())
conn.close()
server.close()Client Side
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 9090))
client.send("Hello Server".encode())
response = client.recv(1024).decode()
print("Server:", response)
client.close()How TCP Socket Works
- Server creates socket
- Server listens for connections
- Client connects to server
- Data is exchanged
- Connection is closed
Output Example
Server Output
Server is waiting...
Connected with ('127.0.0.1', 51234)
Client: Hello ServerClient Output
Server: Hello from serverUDP Socket Programming
UDP is faster but less reliable.
UDP Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("localhost", 9091))
print("UDP Server running")
data, addr = server.recvfrom(1024)
print("Received:", data.decode())
server.sendto("Hello UDP Client".encode(), addr)UDP Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("Hello UDP Server".encode(), ("localhost", 9091))
data, addr = client.recvfrom(1024)
print("Server:", data.decode())
client.close()Difference Between TCP and UDP
| Feature | TCP | UDP |
|---|---|---|
| Connection | Required | Not required |
| Reliability | High | Low |
| Speed | Slower | Faster |
| Use Case | Web, Email | Gaming, Streaming |
Important Socket Methods
Server Methods
bind()→ Assign IP and portlisten()→ Wait for clientsaccept()→ Accept connection
Client Methods
connect()→ Connect to serversend()→ Send datarecv()→ Receive data
Real-World Applications
Socket programming is used in:
- Web servers (HTTP/HTTPS)
- Chat applications
- Online games
- File transfer systems
- Streaming services
- IoT devices
Example: Simple Chat System Idea
# Server handles multiple clients and broadcasts messagesAdvantages of Socket Programming
- Real-time communication
- Cross-platform networking
- Flexible architecture
- Supports distributed systems
Challenges
- Network latency
- Security risks
- Data loss in UDP
- Connection handling complexity
Best Practices
1. Always close sockets
socket.close()2. Handle exceptions properly
try:
pass
except Exception as e:
print(e)3. Use proper buffer size
recv(1024)4. Avoid blocking calls without timeout
Common Mistakes
1. Not closing connections
2. Hardcoding ports without checking availability
3. Not handling disconnected clients
Summary
Socket programming in Python enables communication between devices using TCP and UDP protocols. It forms the backbone of network applications such as chat systems, web servers, and real-time services.
Key Takeaways
- Socket is the core of network communication
- TCP is reliable, UDP is faster
- Client-server model is widely used
- Python
socketmodule simplifies networking - Essential for real-world applications
Mastering socket programming is a major step toward building powerful network-based Python applications.


0 Comments