Vue页面
1、data中声明变量websock
data(){
return{
websock: null,
}
},
2、先写好初始化websocket的方法,然后在mounted中初始化websocket
mounted: function () {
if(this.websock!==null){
console.log(this.websock)
this.websocketclose(this.websock)
}
this.initWebSocket()
},
methods:{
initWebSocket(){ //初始化weosocket
const wsuri = “ws://localhost:5000/api”;//ws地址
this.websock = new WebSocket(wsuri);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
//页面刚进入时开启长连接
let getLanguage=‘{’+
‘“method”:“post”,’+
‘“url”: "’+this.magicalCoderUrl+‘/getLanguage",’+
‘“params”: {’+
‘“Device_ID”: "’+this.bgdeviceID+‘"’+
‘}’+
‘}’
//将request请求的所需的数据发送给python端
this.websocketsend(getLanguage)
console.log(“WebSocket连接成功”);
},
websocketonerror(e) { //错误
console.log(“WebSocket连接发生错误”);
},
websocketonmessage(e){ //数据接收 //python端返回的数据都在这里,根据钩子进行数据处理,e.data即返回的数据
let web_data=JSON.parse(e.data)
let head = web_data.head
let data = web_data.data
if(head===“getLanguage”){
let needLanguage=data.data[0]
this.language = needLanguage.language
}
},
websocketsend(agentData){//数据发送
this.websock.send(agentData);
},
websocketclose(e){ //关闭
console.log("connection closed ");
},
Python端
1、写两个线程,一个是接收网页端发送来的长连接握手,另一个是将所需要回调的websocket进行保存,并循环回复
clients = {} //全局变量,存储接收过的数据,和回调地址
thread7 = threading.Thread(target=WebSocketServer)
thread7.start() //接收网页端的数据
thread8 = threading.Thread(target=asyntest)
thread8.start() //循环回调所需数据
2、线程1
async def ws_handle(websocket: WebSocketServerProtocol, path: str):
# if(websocket in clients):
async for message in websocket:
print("轮询信息:",message) //接收到网页的数据,就是接收到绿色部分的信息
let getLanguage=‘{’+
‘“method”:“post”,’+
‘“url”: "’+this.magicalCoderUrl+‘/getLanguage",’+
‘“params”: {’+
‘“Device_ID”: "’+this.bgdeviceID+‘"’+
‘}’+
‘}’
jsonmsg = json.loads(message)
url = jsonmsg['url']
if ("url" in jsonmsg):
mac = str(jsonmsg)
if str(url) not in str(clients):
clients[mac] = websocket
else:
for item in list(clients.keys()):
if str(url) in str(item):
del clients[item]
clients[mac] = websocket //将回调数据,存储在全局变量clients中
await websocket.send(message)
async def sendmsg(mac, mssage):
websocket = clients[mac]
await websocket.send(mssage)
async def main():
async with websockets.serve(ws_handle, “127.0.0.1”, 5000):
await asyncio.Future() # run forever
def WebSocketServer():
asyncio.run(main())
3、线程2,根据全部变量里的信息,循环回调数据
async def test():
while (True):
global clients
try:
for client in clients:
returnData=SqlData(client) //根据网页传递过来的数据,进行request调用api
if returnData==None:
continue
try:
await sendmsg(client, str(returnData)) # 依次给每个客户端都发一条信息
except Exception as e:
clients={}
except Exception as e:
continue
time.sleep(1)
def SqlData(client):
client = json.loads(str(client).replace(“'”,“”"))
method = client[“method”]
url = client[“url”]
params = client[“params”]
response=""
if method=="get":
response=requests.get(url, params=params)
elif method=="post":
response=requests.post(url, data=params) //获取到api数据
responseHead = str(url).split("/")[-1]
# if responseHead=="getStation":
# print(response.text)
if response.status_code==200: //添加head钩子
responseBox='{"head":"'+responseHead+'","data":'+response.text+'}'
return responseBox
else:
return None
def asyntest():
asyncio.run(test())
def LUN_XUN():
thread7 = threading.Thread(target=WebSocketServer)
thread7.start()
thread8 = threading.Thread(target=asyntest)
thread8.start()