添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hi, I know the websocket can be pinged as a heartbeat, but what if I have to send a specific JSON heartbeat message?

I'm trying to send the following JSON message every minute as a heartbeat to keep the websocket connection alive: { "topic": "phoenix", "event": "heartbeat", "payload": {}, "ref": 0 }

EDIT: But I want to receive messages every 1 second. (msg = await WS.recv() )

My code looks like this:

import asyncio
import json
import websockets
async def socket_connect_WS():
    async with websockets.connect('wss://host.com') as WS:
        await WS.send(json.dumps({"topic": "channel", "event": "phx_join", "payload": {}, "ref": 0}))
        while True:
            msg = await WS.recv()
            print(json.loads(msg))
            await WS.send(json.dumps({"topic": "phoenix", "event": "heartbeat", "payload": {}, "ref": 0 }))
            await asyncio.sleep(1)
loop = asyncio.get_event_loop()
asyncio.ensure_future(socket_connect_WS())
loop.run_forever()

This keeps the websocket open but I would prefer to send the JSON heartbeat message every minute rather than every second.