正向连接
默认服务器监听端口即 ws://127.0.0.1:8898/ws
你的客户端连接框架的Websocket服务器即可收到推送
反向连接
配置 -wsserver 参数即可 -wsserver ws://127.0.0.1:5678/ws
此时框架会作为客户端连接你的WebSocket服务器 若你的服务器异常断线 框架会自动重连你的WebSocket服务器
import asyncio
import json
import random
import requests
import websockets
# websocket server
async def main_logic(websocket, path):
while True:
greeting = await websocket.recv()
EventJson = json.loads(greeting)
EventName = EventJson["CurrentPacket"]["Data"]["EventName"]
print(f"<{EventName} {greeting}")
start_server = websockets.serve(main_logic, '127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import asyncio
import json
import random
import requests
import websockets
#websocket client
SERCIVE_HOST = "127.0.0.1:8898"
async def Wsdemo():
uri = "ws://{}/ws".format(SERCIVE_HOST)
try:
async with websockets.connect(uri) as websocket:
while True:
greeting = await websocket.recv()
EventJson = json.loads(greeting)
EventName = EventJson["CurrentPacket"]["Data"]["EventName"]
print(f"<{EventName} {greeting}")
except Exception as e:
# 断线重连
t = random.randint(5, 8)
print(f"< 超时重连中... { t}", e)
await asyncio.sleep(t)
await Wsdemo()
asyncio.get_event_loop().run_until_complete(Wsdemo())
{
"CurrentPacket": {
"WebConnId": "",
"Data": {N多结构体},
"CurrentWxid": "Wxid_xxxxxxxx"
}