Tornado Websocket 通信
这次使用Python来进行Websocket通信,使用Tornado自带的Websocket库,与游览器自带的api。
目录结构
.
├── static
│ └── index.html
└── websockettest.py
Python
#coding=utf-8
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
client_list = [] #连接用户列表
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self): #连接进入
#print(dir(self)) #康康对象有什么
client_list.append(self)
pass
def on_message(self,message): #消息事件
print(message)
for client in client_list: #将消息发送到所有在线的连接
client.write_message(message)
def on_close(self): #关闭事件
client_list.remove(self)
pass
def check_origin(self,origin): #允许跨域访问
print(origin)
return True
class IndexPageHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
class Application(tornado.web.Application):
def __init__(self):
handlers = [(r'/',IndexPageHandler),(r'/websocket',WebSocketHandler)]
settings = {'template_path':'static'} #设置模板文件目录
tornado.web.Application.__init__(self,handlers,**settings)
if __name__ == '__main__':
app = Application()
tornado.httpserver.HTTPServer(app).listen(80)
tornado.ioloop.IOLoop.instance().start()
Html & JavaSscript
<title>WebSockets Test</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var ws = new WebSocket("ws://ip/websocket"); #你可以在本地保存网页测试(跨域请求)
//ws.onopen = function(){
// ws.send('hello!');
//}
ws.onmessage = function(msg){
$('.message').append("<p>" + msg.data + "</p>");
}
ws.onclose = function(){
$('.message').append("<p>Connection closed</p>");
}
function sendmsg(){
var msg = $("#msg").val();
ws.send(msg);
}
</script>
<div class='message'></div>
<textarea id="msg"></textarea>
<button type="but" onclick="sendmsg()">Send</button>
其他
上次Nodejs的Express-ws网页测试不成功的原因是Socket.io的问题,Socket.io会向(更新:之前不了解Socket.io的工作模式写的不对的话)。socket.io/?EIO=&transport=websocket
请求连 接,只有服务端一起使用Socket.io才能正常连接,使用游览器自带访问正常连接