[英]Send message to a running python websocket client
I'm currently using the websocket-client library to connect to a websocket by following the example code: 我目前正在通过以下示例代码使用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()
however if I try to send additional message to the websocket on-demand (say subscribe additional channels, 但是,如果我尝试按需向websocket发送其他消息(例如订阅其他频道,
ws.send('{ "event": "subscribe", "channel": "sensor5" }')
How would I be able to achieve such? 我将如何实现这一目标? As the ws.run_forever() is already running, how can I get hold of the running websocket instance to submit the message? 由于ws.run_forever()已经在运行,我如何握住正在运行的websocket实例来提交消息?
It's more of a listener than the sender, for sending you can use this : 它比发送者更像是一个侦听器,发送时可以使用以下命令 :
from websocket import create_connection
ws = create_connection("ws://echo.websocket.org/")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
For Listener in your question snippet, you had on_message
对于您的问题on_message
Listener,您有on_message
Of whose implementation you can do: 您可以对其实施:
def on_message(ws, message):
print(message) #do something with the message
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.