Python websockets库是用于在Python中构建WebSocket服务器和客户端的库。参考文档(https://www.yiibai.com/websocket/python-websockets-library.html,https://websockets.readthedocs.io/en/stable/intro.html )
关于async异步文档见(python3.7 https://docs.python.org/zh-cn/3.7/library/asyncio.html#module-asyncio; python3.6 https://docs.python.org/zh-cn/3.6/library/asyncio-task.html#asyncio-example-gather)
#-*-coding:utf-8-*-
import asyncio
import websockets
import json
post_data = {"data":"消息"}
async def send_data():
uri = "ws://127.0.01:9501"
async with websockets.connect(uri) as websocket:
print(bytes(json.dumps(post_data, ensure_ascii=False).encode("utf-8")))
await websocket.send(bytes(json.dumps(post_data, ensure_ascii=False).encode("utf-8")))
greeting = await websocket.recv()
print(greeting)
loop = asyncio.get_event_loop()
loop.run_until_complete(send_data())
loop.close()