简体   繁体   English

Python Websocket 2路通讯

[英]Python Websocket 2-Way Communication

I'm able to get connected and authenticated to the WebSocket, but am unable to send any requests after that.我能够连接到 WebSocket 并对其进行身份验证,但之后无法发送任何请求。

I'd like to be able to send messages to the server to perform different actions.我希望能够向服务器发送消息以执行不同的操作。 Upon connection the on_open(ws) runs as expected, and I'm returned the confirmation on_message that I'm authenticated.连接后, on_open(ws)会按预期运行,并且我会返回确认我已通过身份验证的on_message But after that I can't seem to do anything else.但在那之后,我似乎无法做任何其他事情。

If I put ws.send(MESSAGE) before the ws.run_forever() the WebSocket closes before it can send.如果我将ws.send(MESSAGE)放在 ws.run_forever() 之前,则ws.run_forever()在发送之前关闭。 If I put it after, the WebSocket seems to hang.如果我把它放在后面,WebSocket 似乎挂了。

So my question is, how do I go about sending the WebSocket commands after it's connected and authenticated?所以我的问题是,我如何 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()

As a side note, calling the Websocket from CLI rather than in a script gives me the prompt to enter messages and works allows back and forth communication as expected:作为旁注,从 CLI 而不是在脚本中调用 Websocket 会提示我输入消息,并且允许按预期进行来回通信:

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

It appears that you can throw things into the on_open() function and that will continue even though the on_message function is called anytime there's a message.看来你可以把东西扔进on_open() function ,即使有消息时调用on_message function 也会继续。

I could have sworn I tried this, but getting away from the screen for a while seems to have helped.我本可以发誓我试过这个,但离开屏幕一段时间似乎有帮助。

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