简体   繁体   English

将消息发送到正在运行的python websocket客户端

[英]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.

相关问题 python龙卷风websocket服务器将消息发送到特定客户端 - python tornado websocket server send message to specific client 在python中向特定客户端connectionId Websocket API AWS发送消息? - Send message to specific client connectionId Websocket API AWS in python? Python在Tkinter中发送WebSocket消息 - Python send websocket message in tkinter 如何将来自 python cmd 的输入发送到在同一解释器中运行的高速公路 websocket 客户端? - How do I send input from python cmd to autobahn websocket client running in the same interpreter? 无法将数据发送到 python 中的特定 websocket 客户端 - Unable to send data to a specific websocket client in python 通过Python套接字/ WebSocket客户端发送/接收WebSocket消息 - Sending / receiving WebSocket message over Python socket / WebSocket Client 如何在龙卷风WebSocket中将服务器消息发送到特定客户端 - How to send server message to specific client in tornado websocket python websocket-client,仅在队列中接收最新消息 - python websocket-client, only receive most recent message in queue Quart python:从curl发送websocket广播消息并显示它 - Quart python : send websocket broadcast message from curl and display it 基于Python3的WebSocket服务器,客户端在发送时关闭连接 - Python3 based WebSocket server, client closes connection on send
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM