Python websockets keepalive ping 超时;没有收到关闭帧

Python websockets keepalive ping timeout; no close frame received

我有 20-50 个用户,我想从他们那里获得有关他们是否连接到 Internet 或 Internet 较弱的实时信息

我写了一个 Python 脚本来检查连接并将信息发送到 Django django-channels 中的 Web 服务器 Windows 调度程序中的脚本 运行 从上午 9 点到下午 6 点

脚本

    async def main():
        username = get_username()
        url = "{}{}/".format(LOG_SERVER, username)
        async with websockets.connect(url) as websocket:
            # send info to server
            while True:
                try:
                    loop = asyncio.get_event_loop()
                    data = await loop.run_in_executor(None, 
                                              lambda:get_data(username))
                    await websocket.send(json.dumps(data))
                    await asyncio.sleep(30)
                except websockets.ConnectionClosed as e:
                    print(f'Terminated', e)
                    continue
                except Exception as e:
                    logging.error(e)

if __name__ == "__main__":
    asyncio.run(main())

WebSockets 包:https://websockets.readthedocs.io/

每 30 秒发送一次信息 ping min, max, avg 并确保客户端只要连接到服务器就连接

Django 消费者

async def connect(self):
        try:
            self.username = self.scope['url_route']['kwargs']['username']
            await database_sync_to_async(self.update_user_incr)(self.username)
        except KeyError as e:
            pass
          ......
async def disconnect(self, close_code):
     
        try:
            if(self.username):
                await database_sync_to_async(self.update_user_decr)(self.username)
        except:
            pass
        .......

问题是 python 脚本偶尔会锁定消息

sent 1011 (unexpected error) keepalive ping timeout; no close frame received

no close frame received or sent

我不能自动回拨

如何保持连接打开,或者如果它关闭它会在一小段时间内重新打开,以便前端无法修改在线或离线指示器

我最终重新连接了类似这样的东西

 async for websocket in websockets.connect(url):
        try:
            loop = asyncio.get_event_loop()
            data = await loop.run_in_executor(None, lambda: get_data(username))
            await websocket.send(json.dumps(data))
            await asyncio.sleep(30)
        except websockets.ConnectionClosed as e:
            print(f'Terminated', e)

但我遇到了一个问题,那就是在每次连接时调整用户状态。在这种情况下,你可以使用这个blog and this 来减轻数据库的负载