python - Python - 如何使用 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()
推荐阅读
- laravel - fwrite(): send of 249 bytes failed with errno=10053 已建立的连接被主机中的软件中止
- javascript - 我可以在 reactjs 的类之外声明一个全局变量吗
- reactjs - 卸载 create-react-app 的问题
- java - 在 Spring Boot 2.2.x 上执行多个 mongo 时,没有可用类型为“....mongodb.core.convert.MappingMongoConverter”的合格 bean
- reactjs - 如何将 reacr SSR 应用程序部署到 AWS 并删除端口
- r - 带有 ggplot2 的程序化饼图
- nlp - 提取具有相似项目的实体时的 Dialogflow 问题
- wordpress - 为什么我在向 MemberPress 端点发出请求时收到 rest_forbidden 错误?
- testng - testng 套件结果未提供正确的计数
- python - 在 Python 问题中转换为二进制字符串