How to print streaming information from a websocket(client)?

£可爱£侵袭症+ 提交于 2019-12-21 20:35:10

问题


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.

Is there a better way?

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

I am using the websocket client found here https://pypi.python.org/pypi/websocket-client/


回答1:


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.

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


来源:https://stackoverflow.com/questions/40814369/how-to-print-streaming-information-from-a-websocketclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!