1

python | websocket 对接

 1 year ago
source link: https://benpaodewoniu.github.io/2022/11/09/python180/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

简单的例子

import asyncio

import aiohttp


async def ws():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)

if __name__ == '__main__':
asyncio.run(ws())
print(123)

上面是一个简单的例子,但是,这个例子在 async for msg in ws 陷入了死循环。

import asyncio

import aiohttp


async def ws():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(ws())
print(123)
loop.run_forever()

对接两个 ws

import asyncio

import aiohttp


async def ws_binance():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://fstream.binance.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)


async def ws_mexc():
session = aiohttp.ClientSession()
async with session.ws_connect('wss://wbs.mexc.com/ws', proxy="http://127.0.0.1:1087") as ws:
await ws.send_str('{ "method":"SUBSCRIPTION", "params":["[email protected]@BTCUSDT"] }')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(msg)


if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(ws_binance())
loop.create_task(ws_mexc())
loop.run_forever()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK