ws服务器是单独的,专门用来推送消息。js用来连接ws,发消息。eel程序用户处理消息
ws服务器
import websockets
import asyncio
# 存储所有WebSocket连接的集合
connected_clients = set()
async def websocket_handler(websocket, path):
# 将新的连接添加到集合中
connected_clients.add(websocket)
try:
async for message in websocket:
print("收到消息,开始推送-》:", message)
# 将收到的消息推送给所有连接的客户端
await broadcast(message)
finally:
# 移除断开的连接
connected_clients.remove(websocket)
async def broadcast(message):
# 遍历所有连接的客户端,并将消息发送给每个客户端
for client in connected_clients:
if client.open:
await client.send(message)
async def main():
# 开启WebSocket服务器,并设置WebSocket处理器
async with websockets.serve(websocket_handler, "localhost", 8000):
await asyncio.Future() # Run forever
if __name__ == '__main__':
asyncio.run(main())
eel
import eel
@eel.expose
def handleMessage(message):
#TODO 客户端处理消息
print("收到服务器消息:", message)
eel.init('.')
eel.start('index.html', size=(600, 400),port=8888)
html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
<script type="text/javascript" src="eel.js"></script>
</head>
<body>
<h1>WebSocket Client</h1>
<input id="msg" type="text"> <br>
<button id="send" onclick="send()">发送消息</button>
<div id="messages"></div>
<script type="text/javascript">
let ws;
window.onload = function () {
connectWS()
}
function connectWS() {
ws = new WebSocket("ws://127.0.0.1:8000");
ws.onopen = function() {
writeToScreen("连接到服务器");
};
ws.onmessage = function(event) {
handleServerMessage(event.data);
};
ws.onclose = function() {
};
ws.onerror = function(error) {
writeToScreen("error: " + error);
};
}
function handleServerMessage(message) {
//展示在页面
writeToScreen(message)
//服务器处理消息,或者服务器处理完消息,再展示在页面,这里只是回显
eel.handleMessage(message);
}
function writeToScreen(message) {
const messagesDiv = document.getElementById("messages");
const messageElement = document.createElement("div");
messageElement.textContent = message;
messagesDiv.appendChild(messageElement);
}
function send(){
const messages = document.getElementById("msg").value;
ws.send(messages)
document.getElementById('msg').value = '';
}
</script>
</body>
</html>