1、实现机制
通过心跳机制来实现websocket
连接的保活,客户端定期向服务器发送心跳消息,服务端响应心跳消息。
-
前端实现:前端通过定期发送心跳消息(如每隔10秒)来保持
WebSocket
连接活跃,并处理服务器的响应消息。// 当连接建立时执行 socket.onopen = function(event) { console.log("WebSocket连接已建立.");
// 每隔10秒发送心跳 setInterval(function() { if (socket.readyState === WebSocket.OPEN) { const message = { type: 'ping' }; socket.send(JSON.stringify(message)); console.log("发送心跳消息:", message); } }, 10000); // 10000毫秒即10秒 };
-
服务器端实现:服务器端接收心跳消息(ping),并返回心跳响应(
pong
)。服务器端还需要处理其他类型的消息。async def receive(self, text_data=None, bytes_data=None): try: print(f"接收到消息: {text_data}, 类型: {type(text_data)}") data = json.loads(text_data) # 将 JSON 字符串反序列化为 Python 对象 if data.get('type') == 'ping': response = { "type": "pong", "data": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') } await self.send(text_data=json.dumps(response)) print(f"发送心跳响应: {response}") else: message = data.get('message', 'No message received') response = {"message": message} await self.send(text_data=json.dumps(response)) print(f"发送消息: {response}") except json.JSONDecodeError as e: print(f"JSON 解析错误: {e}") except Exception as e: print(f"处理消息时出错: {e}")
2、传数数据的形式
WebSocket
协议中传输的数据本质上是二进制数据或文本数据。在传输 JSON
数据时,通常会将其序列化为字符串。
- 在前端,使用
JSON.stringify
将对象序列化为JSON
字符串发送到服务器。 - 在服务器端,接收到的是一个字符串,需要使用
json.loads
反序列化回Python
对象。
评论列表,共 0 条评论
暂无评论