一、介绍
# websocket是给浏览器新建一套协议。协议规定:浏览器和服务端连接之后不断开,以此可以完成:服务端向客户端主动推送消息。 # websocket协议额外做的一些前天操作: # - 握手,连接前进行校验 # - 发送数据加密 # pip3 install gevent-websocket 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 "asdfasdf"
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>