如何ping websocket服务器,这样它就不会因为我是id而断开连接

2024-06-28 20:46:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用websocket-client连接到websocket服务器。我连接的服务器似乎希望我定期ping它,否则它会断开我的连接。

当我连接到服务器时,它会向我发送以下消息:

0{"sid":"SomeID","upgrades":[],"pingInterval":25000,"pingTimeout":60000}

这似乎告诉我ping间隔和ping超时。我注意到我的websocket客户机在连接后1分25秒一直处于断开状态。如果你把这些数字加起来60s+25s,你会得到1分25秒。因此,我似乎需要每隔一段时间ping这个服务器,这样它就不会断开我的连接。

如何ping服务器?我试过ws.ping(),但似乎不存在。我需要按预期的格式向服务器发送数据吗?还是有内置的ping命令?

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.serverssite.com/socket.io/?transport=websocket",
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.run_forever()

注意:我在node(不是python)中创建了一个websocket客户机,它在1分25秒后不会关闭。因此,似乎有一些内置的ping,这个python websocket客户端没有。。。

————————————————————————————————————————————————————————————————

尝试设置ping_间隔和ping_超时,但仍在关闭:

2017-11-06 12:49:14.340037---做事

2017-11-06 12:49:14.340309---做事

发送:'\x89\x80\\xd9\xc4\xdd'

2017-11-06 12:49:19.341680---做事

2017-11-06 12:49:19.341958---做事

发送:'\x89\x80\xd9\x06\xef\xa8'

2017-11-06 12:49:24.343426---做事

2017-11-06 12:49:24.343769---做事

发送:“\x89\x80\xe6\x92'\xb8”

发送:'\x88\x823\xfb$\xd10\x13'

closed(在这里调用closed方法,服务器关闭我)


Tags: 服务器messageclose客户机间隔wsonerror
2条回答

我有一个类似的问题,通过用2 ping服务器解决了这个问题。我使用了asyncio和websockets库,只是使用了以下内容来防止websocket关闭:

await ws.send('2')

使用标准的websocket库是类似的。

完整解释

服务器是socket.io这意味着您需要在pingTimeout内向服务器发送一条ping消息2。From socket.io

Encoding - Packet

An encoded packet can be UTF-8 string or binary data. The packet encoding format for a string is as follows

...

0 open Sent from the server when a new transport is opened (recheck)

1 close Request the close of this transport but does not shutdown the connection itself.

2 ping Sent by the client. Server should answer with a pong packet containing the same data

...

Timeouts

The client must use the pingTimeout and the pingInterval sent as part of the handshake (with the open packet) to determine whether the server is unresponsive.

The client sends a ping packet. If no packet type is received within pingTimeout, the client considers the socket disconnected. If a pong packet is actually received, the client will wait pingInterval before sending a ping packet again.

Since the two values are shared between the server and the client, the server will also be able to detect whether the client becomes unresponsive when it does not receive any data within pingTimeout + pingInterval.

从源代码-

def run_forever(self, sockopt=None, sslopt=None,
                ping_interval=0, ping_timeout=None,
                http_proxy_host=None, http_proxy_port=None,
                http_no_proxy=None, http_proxy_auth=None,
                skip_utf8_validation=False,
                host=None, origin=None)

指定ping_interval应该对您有用。

ws.run_forever(ping_interval=70, ping_timeout=10)

相关问题 更多 >