π Python Socket Programming β TCP/UDP Client Server with Code
π§² Introduction β Why Learn Socket Programming?
Socket programming allows Python applications to communicate over the network using standard protocols like TCP and UDP. Whether you’re building a chat app, web server, or IoT communication system, understanding sockets gives you low-level control over how data is sent and received.
π― In this guide, youβll learn:
- What sockets are in networking
- How to create a client-server app in Python
- Differences between TCP and UDP sockets
- Real-world examples and best practices
β What Is a Socket?
A socket is a software endpoint that establishes bidirectional communication between processes across a network.
In Python, the socket module provides low-level networking interfaces for working with TCP/IP and UDP sockets.
π¦ Python socket Module Overview
import socket
Common Constants:
socket.AF_INET: IPv4socket.SOCK_STREAM: TCPsocket.SOCK_DGRAM: UDP
π TCP Socket Programming β Client & Server
π₯οΈ TCP Server Example
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 12345))
server.listen(1)
print("Server listening on port 12345...")
conn, addr = server.accept()
print(f"Connected to {addr}")
data = conn.recv(1024).decode()
print("Received:", data)
conn.send("Hello from server!".encode())
conn.close()
server.close()
π» TCP Client Example
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 12345))
client.send("Hello from client".encode())
response = client.recv(1024).decode()
print("Server says:", response)
client.close()
β Output:
Server listening on port 12345...
Connected to ('127.0.0.1', 60000)
Received: Hello from client
Server says: Hello from server!
π‘ UDP Socket Programming β Client & Server
π₯οΈ UDP Server Example
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 12345))
print("UDP server listening...")
data, addr = server.recvfrom(1024)
print("Received:", data.decode())
server.sendto("ACK from server".encode(), addr)
π» UDP Client Example
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("Ping from client".encode(), ('localhost', 12345))
data, _ = client.recvfrom(1024)
print("Server says:", data.decode())
π§° Real-World Use Cases
| Application Type | Socket Type | Example |
|---|---|---|
| Chat Application | TCP | Bi-directional messaging |
| Online Game | UDP | Low-latency position updates |
| Web Server | TCP | HTTP over TCP |
| IoT Communication | UDP/TCP | Sensors and actuators |
| Remote Shell | TCP | CLI over network |
π§ TCP vs UDP in Socket Programming
| Feature | TCP | UDP |
|---|---|---|
| Type | Connection-oriented | Connectionless |
| Speed | Slower, reliable | Faster, no guarantee |
| Order Guarantee | β Yes | β No |
| Use Cases | File transfer, chat apps, APIs | Streaming, DNS, games |
π Best Practices for Socket Programming
| β Do This | β Avoid This |
|---|---|
Use try-except for error handling | Assuming the network is always available |
Close sockets with socket.close() | Leaving sockets open |
Use threads or asyncio for multiple clients | Blocking server with a single client |
Set timeouts with socket.settimeout() | Waiting indefinitely on reads |
| Validate incoming data | Trusting client blindly |
π Summary β Recap & Next Steps
Python’s socket module enables you to create both client and server applications using TCP and UDP. Itβs perfect for learning how data flows between machines and forms the base for web servers, chat systems, API clients, and more.
π Key Takeaways:
- β
Use the
socketmodule for low-level network communication - β Choose TCP for reliability, UDP for speed
- β
Understand
bind(),listen(),accept(),connect(),send(),recv() - β Always handle network errors and close sockets properly
βοΈ Real-World Relevance:
Socket programming is used in web servers, peer-to-peer systems, real-time games, and IoT.
β FAQ β Python Socket Programming
β What is a socket in Python?
β A socket is a software endpoint used to send/receive data across networks using TCP/IP or UDP.
β What’s the difference between TCP and UDP in sockets?
β
TCP is reliable and ordered.
β
UDP is faster but does not guarantee delivery or order.
β Do I need to install any library?
β
No. Pythonβs socket module is built-in.
β How do I handle multiple clients in a socket server?
β
Use threading, multiprocessing, or asyncio to handle multiple clients concurrently.
β Can I use sockets with localhost?
β
Yes! Use 'localhost' or '127.0.0.1' for testing on your own machine.
Share Now :
