【问题标题】:Send message to a running python websocket client向正在运行的 python websocket 客户端发送消息
【发布时间】:2019-08-08 17:20:56
【问题描述】:

我目前正在使用 websocket-client 库按照示例代码连接到 websocket:

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send('{ "event": "subscribe", "channel": "sensor"+i }')
        time.sleep(1)
    thread.start_new_thread(run, ())


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()

但是,如果我尝试按需向 websocket 发送其他消息(比如订阅其他频道,

ws.send('{ "event": "subscribe", "channel": "sensor5" }')

我怎样才能做到这一点?由于 ws.run_forever() 已经在运行,如何获取正在运行的 websocket 实例来提交消息?

【问题讨论】:

  • 你可以在不同的线程上执行run_forever()。然后你的主线程可以做额外的send()s。虽然我看不出这有什么帮助,因为无论如何你在大约 4 秒后关闭了你的 websocket
  • ooo 感谢您指出这一点,如果我取出 close(),您能告诉我如何管理主线程和后台线程吗?
  • 如果这是您的整个程序(on_* 函数除外),您可以为ws.run_forever 执行thread.start_new_thread 和某种形式的自定义无限循环,您可以在其中添加选项以侦听更多事件.例如,您可以读取标准输入并将每一行按原样发送到套接字。

标签: python websocket


【解决方案1】:

它更像是一个监听器而不是发送者,发送你可以使用this:

from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")

对于你的问题 sn-p 中的 Listener,你有 on_message

您可以执行谁的实现:

def on_message(ws, message):
    print(message) #do  something with the message

【讨论】:

  • 但是如何继续收听来自现有 websocket 连接的新消息?
  • 在建立连接时需要指定on_message、on_error、on_close这些func会带参数对应调用
  • @harshil9968 听起来您应该重新阅读 OPs 问题。据我所知,您并没有给出和回答实际问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2021-12-26
相关资源
最近更新 更多