【问题标题】:How to keep connection alive with async websockets client?如何保持与异步 websockets 客户端的连接?
【发布时间】:2018-11-07 11:53:53
【问题描述】:

我为我找到的herewebsocket 客户端修改了一个示例,如下所示:

import asyncio
import websockets
async def hello(messages):
    async with websockets.connect('ws://localhost:8765') as websocket:
        for m in ('msg1', 'msg2'):
            await websocket.send(m)
            print(f"> {m}")
            greeting = await websocket.recv()
            print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello(['name1', 'name2']))

但是现在,一旦第二个 send() 被执行,我就会遇到异常:

Traceback (most recent call last):
  File "ws-client.py", line 44, in <module>
    main()
  File "ws-client.py", line 41, in main
    asyncio.get_event_loop().run_until_complete(hello(['name1', 'name2']))
  File "/usr/lib64/python3.6/asyncio/base_events.py", line 468, in run_until_complete
    return future.result()
  File "ws-client.py", line 35, in hello
    greeting = await websocket.recv()
  File "/home/frans/.local/lib/python3.6/site-packages/websockets/protocol.py", line 350, in recv
    yield from self.ensure_open()
  File "/home/frans/.local/lib/python3.6/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 = 1000 (OK), no reason

我不太喜欢asyncio - 谁能告诉我我做错了什么?

我也从示例中获取了服务器代码..

【问题讨论】:

    标签: python websocket python-asyncio


    【解决方案1】:

    您更改了客户端,但没有更改服务器,所以问题出在服务器端。只需检查它的代码。

    import asyncio
    import websockets
    
    async def hello(websocket, path):
        name = await websocket.recv()
        print(f"< {name}")
    
        greeting = f"Hello {name}!"
    
        await websocket.send(greeting)
        print(f"> {greeting}")
    
    start_server = websockets.serve(hello, 'localhost', 8765)
    
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    

    在接受新连接后,它等待来自客户端的第一条消息,然后将其发送回并退出处理程序。实际上,它只是关闭了连接。因此,当您的客户端尝试发送第二条消息时,它会失败并出现 Connection closed 错误。

    您可以像这样更改服务器,以重复处理程序有效负载两次。

      async def hello(websocket, path):
          for _ in range(2):  # or while True if you need an infinite echo server
              name = await websocket.recv()
              print(f"< {name}")
    
              greeting = f"Hello {name}!"
    
              await websocket.send(greeting)
              print(f"> {greeting}")
    

    【讨论】:

      【解决方案2】:

      只需检查此链接here 我遇到了类似的问题,即连接长时间没有保持打开状态,我无法真正做我想做的事情,所以我检查了这个例子,没有更多的异常被抛出,主要您应该在代码中更改的内容应该是

      • 而不是
      async def hello(websocket, path):
      

      使用

      @async.coroutine
      def hello (websocket,path)
      

      因此该函数将有资格成为协程生成器

      • 然后将 await 替换为 yield from like
      for m in ('msg1', 'msg2'):
                  yield from websocket.send(m)
                  print(f"> {m}")
                  greeting = yield from websocket.recv()
                  print(f"< {greeting}")
      

      更多细节参见我上面提到的 github repo 哦,正如上面提到的,不要忘记继续消息传递的无限循环

      【讨论】:

        猜你喜欢
        • 2020-10-20
        • 2019-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        相关资源
        最近更新 更多