共计 2132 个字符,预计需要花费 6 分钟才能阅读完成。
Client
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>websocket demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"> </script>
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
function WebSocketTest() {
text = document.getElementById("div_text");
if ("WebSocket" in window) {
// 打开一个 web socket
var ws = new WebSocket("ws://47.100.115.150:9998/handler");
ws.onopen = function () {
// Web Socket 已连接上,使用 send() 方法发送数据
ws.send("Javscript发送的数据");
text.innerHTML = "数据发送中...";
alert("数据发送中...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
text.innerHTML = "收到的数据:" + received_msg;
alert("数据已接收...");
};
ws.onclose = function () {
// 关闭 websocket
text.innerHTML = "连接已关闭...";
alert("连接已关闭...");
};
}
else {
// 浏览器不支持 WebSocket
alert("您的浏览器不支持 WebSocket!");
}
}
</script>
</head>
<body>
<div class="col-md-6 m-5 p-2" id="div_ws">
<a class="btn btn-primary" href="javascript:WebSocketTest()">连接WebSocket</a>
</div>
<div class="col-md-6 border border-primary mx-5 p-2 " id="div_text" style="margin:20px;height:100px;">
display communicate text
</div>
</body>
</html>
Server
#!/usr/bin/python3
# 主要功能:创建1个基本的websocket server, 符合asyncio 开发要求
import asyncio
import websockets
from datetime import datetime
# Set of connected clients
connected_clients = set()
async def handler(websocket, path):
# Add the client to the connected clients set
connected_clients.add(websocket)
try:
# Keep listening for incoming messages from the client
async for message in websocket:
# Broadcast the message to all connected clients
await broadcast(message)
finally:
connected_clients.remove(websocket)
async def broadcast(message):
# Broadcast the message to all connected clients
for client in connected_clients:
await client.send(message)
async def main():
async with websockets.serve(handler, "localhost", 9998):
await asyncio.Future() # run forever
loop = asyncio.get_running_loop() #获取当前event_loop对象
loop.create_task(broadcast()) # 添加新的异步广播任务
if __name__ == "__main__":
asyncio.run(main())
END