代码之家  ›  专栏  ›  技术社区  ›  Danny Tuppeny

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

  •  1
  • Danny Tuppeny  · 技术社区  · 7 年前

    我正在写一些基于 these docs . 服务器应该侦听web套接字并只响应 ping 带有的邮件 pong .

    我在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()
    

    两次,然后关闭连接。当客户端断开连接时,服务器的输出会出现此错误:

    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
    

    根据上面链接的文件:

    这让我相信它应该退出 async for

    1 回复  |  直到 7 年前
        1
  •  1
  •   Danny Tuppeny    7 年前

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

    迭代器产生传入消息。当连接关闭且状态代码为1000(正常)或1001(消失)时,它正常退出。当连接使用任何其他状态代码关闭时,它会引发ConnectionClosed异常。

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