简体   繁体   English

如何与异步 websockets 客户端保持连接?

[英]How to keep connection alive with async websockets client?

I modified an example for a websocket client I found here like this:我修改了我在这里找到的websocket客户端的示例,如下所示:

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']))

But now I'm getting an exception as soon as the second send() gets executed:但是现在一旦第二个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

I'm not so much into asyncio - can someone please tell me what I'm doing wrong?我不太喜欢asyncio - 有人可以告诉我我做错了什么吗?

I took the server code from the example as well..我也从示例中获取了服务器代码..

You changed the client, but didn't change the server, so the problem is on the server side.您更改了客户端,但没有更改服务器,因此问题出在服务器端。 Just check its code.只需检查其代码。

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

After accepting a new connection it waits for the first message from the client, then sends it back and exits the handler.接受新连接后,它等待来自客户端的第一条消息,然后将其发送回并退出处理程序。 In effect, it just closes the connection.实际上,它只是关闭了连接。 So, when your client tries to send the second message, it fails with the Connection closed error.因此,当您的客户端尝试发送第二条消息时,它会因Connection closed错误而失败。

You can change the server like this, to repeat the handler payload twice.您可以像这样更改服务器,以重复处理程序负载两次。

  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}")

just check this link here I faced a similar problem that the connection was not kept open for a long time for me to actually do the things I wanted, so I checked this example and no more exceptions were thrown, the main thing you should change in your code should be只需在此处查看此链接我遇到了类似的问题,即连接长时间未打开以让我真正做我想做的事情,因此我检查了此示例并没有抛出更多异常,您应该更改的主要内容你的代码应该是

  • instead of代替
async def hello(websocket, path):

use

@async.coroutine
def hello (websocket,path)

thus the function will be eligible for becoming a coroutine generator因此该函数将有资格成为协程生成器

  • then replace await with yield from like然后用类似的 yield 替换 await
for m in ('msg1', 'msg2'):
            yield from websocket.send(m)
            print(f"> {m}")
            greeting = yield from websocket.recv()
            print(f"< {greeting}")

for more details see the github repo I mentioned above oh and as the above comment mentioned don't forget the infinite loop for continued messaging有关更多详细信息,请参阅我上面提到的 github repo 哦,正如上面提到的评论,不要忘记继续消息传递的无限循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM