簡體   English   中英

Python Websocket 2路通訊

[英]Python Websocket 2-Way Communication

我能夠連接到 WebSocket 並對其進行身份驗證,但之后無法發送任何請求。

我希望能夠向服務器發送消息以執行不同的操作。 連接后, on_open(ws)會按預期運行,並且我會返回確認我已通過身份驗證的on_message 但在那之后,我似乎無法做任何其他事情。

如果我將ws.send(MESSAGE)放在 ws.run_forever() 之前,則ws.run_forever()在發送之前關閉。 如果我把它放在后面,WebSocket 似乎掛了。

所以我的問題是,我如何 go 關於在連接和驗證后發送 WebSocket 命令?

import websocket
import json

def on_open(ws):
    print("Connection Opened")
    authenticationMsg = {
        "action": "authenticate",
        "data": {
            "key_id": "KEY_ID",
            "secret_key": "SECRET_KEY"
        }
    }
    ws.send(json.dumps(authenticationMsg))

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

def on_error(ws, error):
    print(json.loads(error))

def on_close(ws):
    print("Connection Closed")

socket = "wss://data.alpaca.markets/stream"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close)
ws.run_forever()

作為旁注,從 CLI 而不是在腳本中調用 Websocket 會提示我輸入消息,並且允許按預期進行來回通信:

zackscomputer % python3 -m websocket wss://data.alpaca.markets/stream
Connected to wss://data.alpaca.markets/stream.
>

看來你可以把東西扔進on_open() function ,即使有消息時調用on_message function 也會繼續。

我本可以發誓我試過這個,但離開屏幕一段時間似乎有幫助。

def on_open(ws):
    print("Connection Opened")
    authenticationMsg = {
        "action": "authenticate",
        "data": {
            "key_id": config.alpacaApiKey,
            "secret_key": config.alpacaApiSecretKey
        }
    }
    ws.send(json.dumps(authenticationMsg))

    subscribe = {
        "action":"listen",
        "data": {
            "streams": [WHATEVER I WANT HERE]
        }
    }

    ws.send(json.dumps(subscribe))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM