udp 是通过接收数据的ip地址来判断客户端的,只有接收和发送,不管理客户端的状态
import socket
from collections import defaultdict
# 创建UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', 9999))
# 存储客户端信息和最后活跃时间
clients = {}
print("UDP服务器启动,等待客户端连接...")
while True:
data, client_addr = server_socket.recvfrom(1024)
# 检查是否是已知客户端
if client_addr not in clients:
print(f"新客户端接入: {client_addr}")
clients[client_addr] = {
'last_active': time.time(),
'data': data
}
# 可以发送欢迎消息
server_socket.sendto(b"Welcome to the server!", client_addr)
else:
# 更新已知客户端的活跃时间
clients[client_addr]['last_active'] = time.time()
clients[client_addr]['data'] = data
print(f"收到来自 {client_addr} 的消息: {data.decode()}")
# 可以定期清理不活跃的客户端
# ...
websocket必须要和客户端握手,确认都在线,才可以发送,需要管理客户状态,带有http认证状态
import asyncio
import websockets
from datetime import datetime
# 存储活跃客户端
connected_clients = set()
async def handle_connection(websocket, path):
# 新客户端连接时触发
client_id = f"{websocket.remote_address[0]}:{websocket.remote_address[1]}"
print(f"[{datetime.now()}] 新客户端接入: {client_id}")
connected_clients.add(websocket)
try:
# 发送欢迎消息
await websocket.send("欢迎连接到WebSocket服务器!")
# 保持连接并处理消息
async for message in websocket:
print(f"收到来自 {client_id} 的消息: {message}")
# 可以回复消息或广播给其他客户端
await websocket.send(f"服务器已收到: {message}")
except websockets.exceptions.ConnectionClosed:
print(f"[{datetime.now()}] 客户端断开: {client_id}")
finally:
connected_clients.remove(websocket)
# 启动WebSocket服务器
start_server = websockets.serve(
handle_connection,
"0.0.0.0",
8765,
# 可选:设置连接限制和超时
max_size=2**20, # 1MB最大消息
ping_interval=20, # 20秒发送一次ping
ping_timeout=60, # 60秒无响应断开
)
print("WebSocket服务器启动,监听 ws://0.0.0.0:8765")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()