[英]Python - How to send heartbeat using websocket-client?
服務器要求客戶端每 30 秒發送一次心跳以保持連接處於活動狀態。 如何使用 python websocket-client 庫來實現這一點?
import websocket
def on_open(ws):
pass
def on_close(ws):
pass
def on_message(ws, message):
pass
socket = "wss:// the rest of the url"
ws = websocket.WebSocketApp(socket, on_open=on_open,on_message=on_message)
ws.run_forever()
在 ws.run_forever() 之后沒有代碼運行。 如何發送消息? 謝謝
在庫文檔中有一個長壽命連接示例。 為您的用例修改它,它應該看起來像這樣。 我在兩次心跳之間使用了 28 秒,因為您說 30 秒是預期的持續時間。 如果這很關鍵,我將使用 14 秒來使其對網絡問題更加健壯。
import websocket
try:
import thread
except ImportError:
import _thread as thread
import time
.. code removed for brevity ..
def on_open(ws):
def run(*args):
while True:
time.sleep(28)
ws.send("Ping")
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
run_forever 有 ping_interval 參數。 例如。 ws.run_forever( ping_interval=14) 可用於您的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.