Python async UDP server
- User
Python async UDP server
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Python async UDP server
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's how to create an asynchronous UDP server in Python using asyncio:
import asyncio
class UDPServerProtocol:
def __init__(self):
self.transport = None
def connection_made(self, transport):
self.transport = transport
print("UDP server started")
def datagram_received(self, data, addr):
message = data.decode('utf-8')
print(f"Received from {addr}: {message}")
# Echo the message back
response = f"Echo: {message}"
self.transport.sendto(response.encode('utf-8'), addr)
def error_received(self, exc):
print(f"Error received: {exc}")
async def main():
# Get event loop
loop = asyncio.get_running_loop()
# Create UDP server
transport, protocol = await loop.create_datagram_endpoint(
lambda: UDPServerProtocol(),
local_addr=('localhost', 8888)
)
print("UDP server listening on localhost:8888")
try:
# Keep the server running
await asyncio.sleep(3600) # Run for 1 hour
finally:
transport.close()
if __name__ == "__main__":
asyncio.run(main())
import asyncio
import json
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class UDPServerProtocol:
def __init__(self, message_handler=None):
self.transport = None
self.message_handler = message_handler or self.default_handler
def connection_made(self, transport):
self.transport = transport
logger.info("UDP server started")
def datagram_received(self, data, addr):
try:
# Process message asynchronously
asyncio.create_task(self.handle_message(data, addr))
except Exception as e:
logger.error(f"Error processing message from {addr}: {e}")
async def handle_message(self, data, addr):
try:
message = data.decode('utf-8')
logger.info(f"Received from {addr}: {message}")
response = await self.message_handler(message, addr)
if response:
self.transport.sendto(response.encode('utf-8'), addr)
except Exception as e:
logger.error(f"Error handling message from {addr}: {e}")
error_response = json.dumps({"error": "Invalid message format"})
self.transport.sendto(error_response.encode('utf-8'), addr)
async def default_handler(self, message, addr):
# Simple echo handler
return f"Echo: {message}"
def error_received(self, exc):
logger.error(f"Error received: {exc}")
async def create_udp_server(host='localhost', port=8888, handler=None):
loop = asyncio.get_running_loop()
transport, protocol = await loop.create_datagram_endpoint(
lambda: UDPServerProtocol(handler),
local_addr=(host, port)
)
logger.info(f"UDP server listening on {host}:{port}")
return transport, protocol
async def main():
# Custom message handler
async def json_handler(message, addr):
try:
data = json.loads(message)
response = {
"received": data,
"timestamp": asyncio.get_event_loop().time(),
"client": f"{addr[0]}:{addr[1]}"
}
return json.dumps(response)
except json.JSONDecodeError:
return json.dumps({"error": "Invalid JSON"})
transport, protocol = await create_udp_server(
host='localhost',
port=8888,
handler=json_handler
)
try:
# Keep server running indefinitely
while True:
await asyncio.sleep(1)
except KeyboardInterrupt:
logger.info("Shutting down server...")
finally:
transport.close()
if __name__ == "__main__":
asyncio.run(main())
import asyncio
import json
async def udp_client():
# Create UDP socket
loop = asyncio.get_running_loop()
transport, protocol = await loop.create_datagram_endpoint(
lambda: asyncio.DatagramProtocol(),
remote_addr=('localhost', 8888)
)
# Send test messages
messages = [
"Hello, UDP server!",
json.dumps({"name": "test", "value": 123}),
"Another message"
]
for msg in messages:
transport.sendto(msg.encode('utf-8'))
await asyncio.sleep(1)
transport.close()
if __name__ == "__main__":
asyncio.run(udp_client())
The async UDP server provides several advantages:
Non-blocking: The server can handle multiple clients simultaneously without blocking on any single operation.
Protocol-based: Uses asyncio's datagram protocol interface for clean separation of concerns.
Error handling: Includes proper exception handling for malformed messages and network errors.
Customizable: Easy to extend with custom message handlers for different protocols or data formats.
Logging: Built-in logging for monitoring server activity and debugging.
The server will automatically handle incoming UDP packets, process them asynchronously, and send responses back to clients. You can customize the message handling logic by providing your own handler function to process different types of messages or implement specific protocols.
datagram_received() works asynchronous?
No, datagram_received() itself is not an asynchronous method - it's a synchronous callback that runs on the event loop. However, you can handle the processing asynchronously within it.
import asyncio
import time
class UDPServerProtocol:
def datagram_received(self, data, addr):
# This method is synchronous!
# If you do blocking work here, it blocks the entire event loop
print(f"Received from {addr}: {data.decode()}")
# ❌ DON'T do this - blocks the event loop
# time.sleep(2) # This would freeze the entire server
# ✅ Instead, create an async task for processing
asyncio.create_task(self.process_message_async(data, addr))
async def process_message_async(self, data, addr):
# Now we're in async context and can use await
await asyncio.sleep(2) # Non-blocking delay
response = f"Processed: {data.decode()}"
self.transport.sendto(response.encode(), addr)
class UDPServerProtocol:
def __init__(self):
self.transport = None
self.active_tasks = set()
def datagram_received(self, data, addr):
# Create task and track it
task = asyncio.create_task(self.handle_message(data, addr))
self.active_tasks.add(task)
task.add_done_callback(self.active_tasks.discard)
async def handle_message(self, data, addr):
# Async processing here
await asyncio.sleep(0.1) # Simulate async work
message = data.decode()
response = await self.process_business_logic(message)
self.transport.sendto(response.encode(), addr)
async def process_business_logic(self, message):
# Example: database lookup, API call, etc.
await asyncio.sleep(0.5)
return f"Processed: {message}"
class UDPServerProtocol:
def __init__(self):
self.transport = None
self.message_queue = asyncio.Queue()
self.workers_started = False
def connection_made(self, transport):
self.transport = transport
if not self.workers_started:
# Start background workers
for i in range(3): # 3 worker tasks
asyncio.create_task(self.message_worker(i))
self.workers_started = True
def datagram_received(self, data, addr):
# Just queue the message - non-blocking
try:
self.message_queue.put_nowait((data, addr))
except asyncio.QueueFull:
print(f"Queue full, dropping message from {addr}")
async def message_worker(self, worker_id):
while True:
try:
data, addr = await self.message_queue.get()
await self.process_message(data, addr, worker_id)
self.message_queue.task_done()
except Exception as e:
print(f"Worker {worker_id} error: {e}")
async def process_message(self, data, addr, worker_id):
print(f"Worker {worker_id} processing message from {addr}")
await asyncio.sleep(1) # Simulate work
response = f"Worker {worker_id}: {data.decode()}"
self.transport.sendto(response.encode(), addr)
Here's a demonstration of blocking vs non-blocking:
import asyncio
import time
class BlockingUDPProtocol:
def datagram_received(self, data, addr):
# ❌ Blocking - freezes entire server
time.sleep(2) # Simulates slow processing
response = f"Blocking response: {data.decode()}"
self.transport.sendto(response.encode(), addr)
class NonBlockingUDPProtocol:
def datagram_received(self, data, addr):
# ✅ Non-blocking - server stays responsive
asyncio.create_task(self.handle_async(data, addr))
async def handle_async(self, data, addr):
await asyncio.sleep(2) # Non-blocking delay
response = f"Async response: {data.decode()}"
self.transport.sendto(response.encode(), addr)
# Test with multiple concurrent clients
async def test_server_responsiveness():
# The non-blocking version will handle multiple clients simultaneously
# The blocking version will process them one by one, making clients wait
pass
datagram_received() is synchronous - it runs immediately when data arrives and should return quickly.
For async processing, create tasks using asyncio.create_task() or use queues with background workers.
Avoid blocking operations in datagram_received() - use await in separate async functions instead.
Concurrent handling is achieved by creating multiple tasks, not by making datagram_received() async.
The asyncio UDP server can handle thousands of concurrent connections efficiently when you use these patterns correctly!