Python连接Websocket读写内容

Python连接Websocket读写内容, 连接ws成功之后,一边读一边写

#coding=utf8
#pip install websockets
import websockets
import asyncio

WS_URL = "ws://..."
HEART = '{"code":0,"action":"heart", "data":{"timeStr": "2023-05-19", "msg":"test"}}'

async def read(websocket):
    while (True):
        msg = await websocket.recv()
        print(f"<<<: {msg}")

async def hello():
    uri = WS_URL
    async with websockets.connect(uri) as websocket:
        asyncio.create_task(read(websocket))

        while (True):
            await websocket.send(HEART)
            print(f">>> {HEART}")
            await asyncio.sleep(3)

if __name__ == "__main__":
    asyncio.run(hello())

你可能感兴趣的:(python,websocket,开发语言)