WebSocket 在烧瓶和龙卷风中的应用
Posted 拜悦神教
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebSocket 在烧瓶和龙卷风中的应用相关的知识,希望对你有一定的参考价值。
a. 安装
pip3 install gevent-websocket
作用:
- 处理Http、Websocket协议的请求 -> socket
- 封装Http、Websocket相关数据 -> request
b. 基本结构
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
@app.route('/test')
def test():
ws = request.environ.get('wsgi.websocket')
ws.receive()
ws.send(message)
ws.close()
return render_template('index.html')
if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 5000,), app, handler_class=WebSocketHandler)
http_server.serve_forever()
c. WEB聊天室:
后端:
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from flask import Flask,render_template,request
import pickle
app = Flask(__name__)
app.secret_key = 'xfsdfqw'
@app.route('/index')
def index():
return render_template('index.html')
WS_LIST = []
@app.route('/test')
def test():
ws = request.environ.get('wsgi.websocket')
if not ws:
return '请使用WebSocket协议'
# websocket连接已经成功
WS_LIST.append(ws)
while True:
# 等待用户发送消息,并接受
message = ws.receive()
# 关闭:message=None
if not message:
WS_LIST.remove(ws)
break
for item in WS_LIST:
item.send(message)
return "..."
if __name__ == '__main__':
http_server = WSGIServer(('0.0.0.0', 5000,), app, handler_class=WebSocketHandler)
http_server.serve_forever()
前端:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<style>
.msg-item{
padding: 5px;
border: 1px;
margin: 0 5px;
}
</style>
</head>
<body>
<h1>首页</h1>
<div>
<h2>发送消息</h2>
<input id="msg" type="text" /> <input type="button" value="发送" onclick="sendMsg()">
<h2>接收消息</h2>
<div id="container">
</div>
</div>
<script src="/static/jquery-3.3.1.min.js"></script>
<script>
ws = new WebSocket('ws://192.168.12.42:5000/test');
ws.onmessage = function (event) {
var tag = document.createElement('div');
tag.className = 'msg-item';
tag.innerText = event.data;
$('#container').append(tag);
}
function sendMsg() {
ws.send($('#msg').val());
}
</script>
</body>
</html>
d. tornado.websocket示例
import tornado
from tornado.web import Application
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
class IndexHandler(RequestHandler):
def get(self, *args, **kwargs):
# self.write('Hello World')
self.render('index.html')
def post(self, *args, **kwargs):
user = self.get_argument('user')
self.write('成功')
WS_LIST = []
class MessageHandler(WebSocketHandler):
def open(self, *args, **kwargs):
WS_LIST.append(self)
def on_message(self, message):
for ws in WS_LIST:
ws.write_message(message)
def on_close(self):
WS_LIST.remove(self)
settings = {
'template_path':'templates',
'static_path':'static',
}
app = Application([
(r"/index", IndexHandler),
(r"/message", MessageHandler),
],**settings)
if __name__ == '__main__':
app.listen(address='0.0.0.0',port=9999)
tornado.ioloop.IOLoop.instance().start()
以上是关于WebSocket 在烧瓶和龙卷风中的应用的主要内容,如果未能解决你的问题,请参考以下文章