gpt4 book ai didi

python - 为什么这个简单的 websocket 代码会在客户端断开连接时抛出异常?

转载 作者:太空宇宙 更新时间:2023-11-03 21:43:15 24 4
gpt4 key购买 nike

我正在编写一些基于 these docs 的简单 Web 套接字代码。服务器应监听 Web 套接字并仅使用 pong 响应 ping 消息。

我在 Python3 上运行,服务器代码如下所示:

import asyncio
import websockets
from jsonrpcserver.aio import methods
from jsonrpcserver.response import NotificationResponse

@methods.add
async def ping():
return 'pong'

async def accept_connection(websocket, path):
async for request in websocket:
response = await methods.dispatch(request)
if not response.is_notification:
await websocket.send(str(response))

start_server = websockets.serve(accept_connection, 'localhost', 5000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

客户端位于 Dart 中,只需调用 ping 两次,然后关闭连接。当客户端断开连接时,服务器的输出会收到此错误:

Dannys-MacBook:pythonws danny$ python3 server.py 
--> {"jsonrpc":"2.0","method":"ping","id":0}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 0}
--> {"jsonrpc":"2.0","method":"ping","id":1}
<-- {"jsonrpc": "2.0", "result": "pong", "id": 1}
Error in connection handler
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/websockets/server.py", line 152, in handler
yield from self.ws_handler(self, path)
File "server.py", line 11, in accept_connection
async for request in websocket:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/websockets/py36/protocol.py", line 15, in __aiter__
yield await self.recv()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/websockets/protocol.py", line 350, in recv
yield from self.ensure_open()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/websockets/protocol.py", line 512, in ensure_open
self.close_code, self.close_reason) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1005 (no status code [internal]), no reason

根据上面链接的文档:

Iteration terminates when the client disconnects.

这让我相信它应该退出async for循环而不是抛出?

最佳答案

https://www.pydoc.io/pypi/websockets-6.0/autoapi/protocol/index.html

The iterator yields incoming messages. It exits normally when the connection is closed with the status code 1000 (OK) or 1001 (going away). It raises a ConnectionClosed exception when the connection is closed with any other status code.

以客户端的 1000 状态关闭可防止出现异常。

关于python - 为什么这个简单的 websocket 代码会在客户端断开连接时抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com