项目结构
websocket server端代码
在实际开发中用到了跨域,所以这里添加了跨域
而且在tornado中如果websocket和发起websocket请求的网址不同源,会报403错误,所以在这里重写了check_origin
这个方法。
from abc import ABC
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
class WebSocketHandler(tornado.websocket.WebSocketHandler, ABC):
def set_default_headers(self):
"""
该方法实现跨域
"""
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
def check_origin(self, origin: str):
"""
重写同源检查方法
"""
return True
def open(self):
self.write_message("打开了连接!")
def on_message(self, message):
self.write_message("Your message was: " + message)
print(message)
self.write_message("hahaha")
def on_close(self):
self.write_message("关闭了连接!")
class MainPageHandler(tornado.web.RequestHandler, ABC):
def get(self):
self.render("websocket_client.html")
application = tornado.web.Application(
handlers=[
(r"/", MainPageHandler),
(r"/ws", WebSocketHandler),
],
template_path="templates",
debug=False,
)
if __name__ == '__main__':
server = tornado.httpserver.HTTPServer(application)
server.listen(8889)
tornado.ioloop.IOLoop.current().start()
websocket client端代码
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8">
<title>websocket_test</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<input type="button" onclick="sendMsg()" value="Send">
<script type="text/javascript">
function sendMsg() {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://127.0.0.1:8889/ws");
ws.onopen = function () {
ws.send("Hello world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
}
}
</script>
</body>
</html>