简体   繁体   中英

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:

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,

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?

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

Of whose implementation you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM