如何在Python中创建一个WebSocket连接?

vulvrdjw  于 2022-11-11  发布在  Python
关注(0)|答案(2)|浏览(228)

我正在尝试使用以下代码创建一个WebSocket连接(只是为了进行测试连接):

async def webSocket():

async with websockets.connect("wss://push1-v2.kucoin.com") as test:
    await test.send("/api/v1/bullet-public")
    result = await test.recv()
    print(result)

if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(webSocket())

结果应该是这样一个json响应:

{
"code": "200000",
"data": {

    "instanceServers": [
        {
            "endpoint": "wss://push1-v2.kucoin.com/endpoint",
            "protocol": "websocket",
            "encrypt": true,
            "pingInterval": 50000,
            "pingTimeout": 10000
        }
    ],
    "token": "vYNlCtbz4XNJ1QncwWilJnBtmmfe4geLQDUA62kKJsDChc6I4bRDQc73JfIrlFaVYIAE0Gv2--MROnLAgjVsWkcDq_MuG7qV7EktfCEIphiqnlfpQn4Ybg==.IoORVxR2LmKV7_maOR9xOg=="
}

}
相反,当我执行代码时,我得到以下错误:

for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

有没有可能有一个设置我必须改变到我的python设置?我使用的是3. 9版本。

ecbunoof

ecbunoof1#

第一次POST(/api/v1/bullet-public)的目标是API HTTPS,即https://api.kucoin.com/
您可以使用命令行或终端手动尝试:

curl -i -X POST https://api.kucoin.com/api/v1/bullet-public
rqmkfv5c

rqmkfv5c2#

我能够使用请求获得成功响应。

import requests

url = 'https://api.kucoin.com/api/v1/bullet-public'
params = {"code": 200000}

r = requests.post(url=url, data=params)
print(r.text)

输出量:

{"code":"200000","data":{"token":"2neAiuYvAU61ZDXANAGAsiL4-iAExhsBXZxftpOeh_55i3Ysy2q2LEsEWU64mdzUOPusi34M_wGoSf7iNyEWJ8rOsUMiCDkA8T3XpfNKOQvf0ImYa78XstiYB9J6i9GjsxUuhPw3BlrzazF6ghq4L7-hL6el-nEq88XUTYg8sSU=rdcepcTiY0DA==","instanceServers":[{"endpoint":"wss://ws-api.kucoin.com/endpoint","encrypt":true,"protocol":"websocket","pingInterval":18000,"pingTimeout":10000}]}}

我的主要错误是使用requests.get而不是requests.postKucoin API文档中指定的www.example.com。-https://docs.kucoin.com/#apply-connect-token

相关问题