前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var websocket = null;
//判断当前浏览器是否支持WebSocket,是则创建WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:9999/websocket");
}else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
console.log("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
console.log("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
console.log(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
console.log("WebSocket连接关闭");
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(JSON.stringify({
"data":1
}));
}
//如果websocket连接还没断开就关闭了窗口,后台server端会抛异常。
//所以增加监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接
window.onbeforeunload = function () {
closeWebSocket();
}
</script>
</head>
<body>
<div id="text">这是一段文字信息</div>
<button onclick="send()">点击发送</button>
</body>
</html>
后端python代码
import json
import logging
from abc import ABC
import tornado.websocket
import tornado.escape
import uuid
from tornado.web import RequestHandler
class WebSocketHandler(RequestHandler, tornado.websocket.WebSocketHandler, ABC):
bao_cons = set()
bao_waiters = {}
global con_key
def open(self):
sole_id = str(uuid.uuid4()).upper()
self.con_key = sole_id
self.bao_waiters["{}".format(sole_id)] = self
self.bao_cons.add(self)
self.write_message({"websocket_sole_id": sole_id})
logging.info("websocket opened!")
print(self.bao_cons)
def on_message(self, message):
if message == "close":
self.close()
return
try:
parse_data = tornado.escape.json_decode(message)
print(parse_data)
if parse_data["user"] and parse_data["content"]:
user = parse_data["user"]
content = parse_data["content"]
if not user or not content:
logging.info("Date is wrong!")
return
else:
for key in self.bao_waiters.keys():
if key == user:
try:
self.bao_waiters[key].write_message("{}".format(content))
except Exception as e:
logging.info(e)
finally:
logging.info("process finished!")
except:
for con in self.bao_cons:
con.write_message(message)
def check_origin(self, origin: str):
return True
def allow_draft76(self):
return True
def on_close(self):
self.bao_cons.remove(self)
self.bao_waiters.pop(self.con_key)
logging.info("websocket closed!")
print(self.bao_cons)