Socket Communication
Understanding Sockets
Sockets are fundamental communication endpoints that enable network communication between different devices and applications. They provide a mechanism for programs to exchange data across networks.
Socket Types
1. Stream Sockets (TCP)
graph LR
A[Client Socket] -->|Establish Connection| B[Server Socket]
B -->|Data Transfer| A
A -->|Close Connection| B
Socket Type |
Protocol |
Characteristics |
Stream Sockets |
TCP |
Reliable, connection-oriented |
Datagram Sockets |
UDP |
Lightweight, connectionless |
2. Datagram Sockets (UDP)
Socket Communication Workflow
Client-Server Model
## TCP Server Example
import socket
def tcp_server():
## Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Bind to specific address and port
server_socket.bind(('localhost', 8000))
## Listen for incoming connections
server_socket.listen(1)
while True:
## Accept client connection
client_socket, address = server_socket.accept()
## Receive data
data = client_socket.recv(1024)
print(f"Received: {data.decode()}")
## Send response
client_socket.send("Message received".encode())
## Close connection
client_socket.close()
## Corresponding Client
def tcp_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8000))
## Send data
client_socket.send("Hello, Server!".encode())
## Receive response
response = client_socket.recv(1024)
print(f"Server response: {response.decode()}")
client_socket.close()
Advanced Socket Concepts
1. Non-Blocking Sockets
import socket
import select
def non_blocking_socket():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setblocking(0)
## Configure non-blocking mode
server_socket.bind(('localhost', 8001))
server_socket.listen(5)
## Use select for managing multiple connections
inputs = [server_socket]
while inputs:
readable, _, _ = select.select(inputs, [], [], 1)
for s in readable:
if s is server_socket:
## Handle new connections
client_socket, address = s.accept()
inputs.append(client_socket)
Socket Communication Best Practices
- Handle exceptions carefully
- Implement proper connection management
- Use timeouts to prevent hanging
- Secure socket communications
- Minimize data transfer overhead
- Use appropriate buffer sizes
- Implement efficient connection pooling
LabEx Recommendation
When learning socket programming, start with simple examples and gradually increase complexity. Practice implementing both server and client-side logic.
Conclusion
Socket communication is a powerful technique for network programming, providing flexible and efficient data exchange mechanisms across different systems and networks.