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的websockets库建立WebSocket连接并实现数据的异步读取和发送。在一个无限循环中,它不断地读取接收到的消息并打印,同时每隔3秒发送一个心跳包。
578

被折叠的 条评论
为什么被折叠?



