如何从websocket(客户端)打印流信息? [英] How to print streaming information from a websocket(client)?

查看:881
本文介绍了如何从websocket(客户端)打印流信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用websocket打印流信息.服务器间歇性地发送信息.我正在使用下面的python代码中的while True:循环来打印它.

I want to print streaming information using a websocket. The server is sending out information intermittently. I am printing it using the while True: loop in the python code below.

有更好的方法吗?

from websocket import create_connection


def connect_Bitfinex_trades():
    ws = create_connection("wss://api.sample.com:3000/ws")
    print "Sent"
    while True:
        print "Receiving..."
        result = ws.recv()
        print "Received '%s'" % result

我正在使用在此处> https://pypi.python.org/pypi/websocket-client/

推荐答案

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

I personally find this a better solution to getting/printing the information from a websocket. This example I found on the developer's website of the websocket-client.

如果您注意到了,此示例将使用run_forever方法,该方法将使websocket连接保持打开状态并接收消息,直到发生错误或连接关闭为止.

If you noticed, this example uses the run_forever method that will keep the websocket connection open and receive messages until an error occurs or connection is closed.

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

这篇关于如何从websocket(客户端)打印流信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆