python 的webscokect简单应用
python使用webscoket的小案例,这里只做了一些简答的发送与应答,具体的逻辑代码可以根据应用场景进行调配。
python代码:
import websockets
import websockets.legacy
import websockets.legacy.server
import socket
import asyncio
# 服务器端主逻辑
async def run(websocket, path):
while True:
try:
# 获取前端传来的参数
getlist = await websocket.recv()
print(getlist)
# 发送信息到前端
await websocket.send("收到")
except websockets.ConnectionClosed:
print("main remove ConnectionClosed")
break
except websockets.InvalidState:
print("InvalidState...") # 无效状态
break
except Exception as e:
print("Exception:", e)
break
# 程序入口
if __name__ == '__main__':
# 获取本机计算机名称
hostname = socket.gethostname()
# 获取本机ip
#(为了方便测试直接获取本机IP,如是其他IP请自己根据需求改动)
ip = socket.gethostbyname(hostname)
print(ip)
# 根据本机IP地址开启webscoket服务
asyncio.get_event_loop().run_until_complete(websockets.serve(run, ip, 8181))
asyncio.get_event_loop().run_forever()
前端页面代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webscokect</title>
</head>
<body>
<button id="con_webscokect" onclick="con()">连接</button>
<button onclick="send()">发送</button>
</body>
<script>
let scokect=null;
function con(){
let that=this
var getip = "192.168.11.22"
if ("WebSocket" in window) {
if(!scokect){
var ws = new WebSocket("ws://"+getip+":8181")
scokect=ws;
ws.onopen = function() {
alert("连接成功")
scokect.send("hello")
document.getElementById("con_webscokect").innerHTML="断开"
};
//接收服务端传来的信息
ws.onmessage = function(evt) {
console.log(evt)
// console.log(evt.data)
alert(evt.data)
}
//------------------------------------------------------------------------------
// 连接断开时的反馈
ws.onclose = function(evt){
alert("连接已断开")
//给断开标志
};
//连接错误时的反馈
ws.onerror = function(evt){
alert("连接失败")
console.log("WebSocketError!");
};
return scokect
}
else{
scokect.close();
scokect=null;
document.getElementById("con_webscokect").innerHTML="连接"
}
// ws.close();
}
else{
console.log("不支持webscokect")
}
}
function send(){
try{
scokect.send("hello")
}catch{
alert('请先连接')
}
}
</script>
</html>