【问题标题】:Difference between websocket and websocketswebsocket 和 websocket 的区别
【发布时间】:2020-05-20 08:48:47
【问题描述】:

我不明白 websocket(websocket 客户端)和 websockets 之间的区别。 我想了解其中的区别,以了解哪个是最佳的。

我有一个似乎做同样事情的代码。

import websockets
import asyncio
import json

async def capture_data():
    uri = "wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD"
    #uri = "wss://www.bitmex.com/realtime"
    async with websockets.connect(uri) as websocket:
        while True:
            data = await websocket.recv()
            data = json.loads(data)
            try :
                #print('\n', data['data'][0]["lastPrice"])
                print('\n', data)
            except KeyError:
                continue


asyncio.get_event_loop().run_until_complete(capture_data())
import websocket
import json

def on_open(ws):
    print("opened")

    auth_data = {
        'op': 'subscribe',
        'args': ['instrument:XBTUSD']
    }
    ws.send(json.dumps(auth_data))

def on_message(ws, message):
    message = json.loads(message)
    print(message)

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


socket = "wss://www.bitmex.com/realtime"                 
ws = websocket.WebSocketApp(socket, 
                            on_open=on_open, 
                            on_message=on_message,
                            on_close=on_close)     
ws.run_forever()

编辑:

Python 是否强大到足以通过 websocket 接收大量数据? 在高流量时,我每秒可能会收到数千条消息,甚至在短时间内会收到数万条消息。

我已经看到很多关于 Nodejs 的东西可能比 python 更好,但我不知道 js,即使我只是从互联网上复制代码,我也不确定如果有的话我不会浪费时间将数据发送到我的 python 脚本,然后进行处理。

【问题讨论】:

  • 刚遇到这个,老实说我感觉好像差别不大,只有两种方式,我很喜欢可以指定WebSocketApp()的回调功能,读起来很直观。

标签: python python-3.x websocket python-asyncio


【解决方案1】:

websocket-client 实现了 WebSocketApp,它更像 JavaScript 的 websocket 实现。

我更喜欢 WebSocketApp 作为线程运行:

socket = "wss://www.bitmex.com/realtime"                 
ws = websocket.WebSocketApp(socket, 
                            on_open=on_open, 
                            on_message=on_message,
                            on_close=on_close) 

wst = threading.Thread(target=lambda: ws.run_forever())
wst.daemon = True
wst.start()

# your code continues here ...

现在你有了异步 WebSocket。您的主框架程序正在运行,每次收到消息时,都会调用函数on_message。 on_message 自动处理消息,无需主机中断。

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2014-06-04
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2020-11-27
    • 2021-08-12
    相关资源
    最近更新 更多