How to print streaming information from a websocke

2020-07-18 07:35发布

问题:

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