如何从websocket(客户端)打印流信息?

时间:2016-11-26 02:29:27

标签: python websocket client

我想使用websocket打印流信息。服务器间歇性地发送信息。我在下面的python代码中使用char* s = "pax byb zic abbc"; int n = strlen(s); int a[n], c[n]; a[0] = (s[0] == 'a') ? 1 : 0; for (int k = 1; k < n; ++k) a[k] = a[k - 1] + ((s[k] == 'a') ? 1 : 0); c[n - 1] = (s[n - 1] == 'c') ? 1 : 0; for (int k = n - 2; k >= 0; --k) c[k] = c[k + 1] + ((s[k] == 'c') ? 1 : 0); int r = 0; for (int k = 0; k < n; ++k) if (s[k] == 'b') r += a[k] * c[k]; printf("%d\n", r); 循环打印它。

有更好的方法吗?

while True:

我正在使用此处找到的websocket客户端https://pypi.python.org/pypi/websocket-client/

1 个答案:

答案 0 :(得分:2)

我个人认为这是从websocket获取/打印信息的更好解决方案。我在websocket-client的开发者网站上找到了这个例子。

如果您注意到,此示例使用run_forever方法保持websocket连接打开并接收消息,直到发生错误或连接关闭。

import websocket
import thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    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()