1 installation geventwebsocket
pip install gevent-websocket
Video address: www.bilibili.com/video/BV1Q7…
2 Front-end code
<div id="mesg" style="width: 400px; height: 400px; background: #aaaaaa; font-size: 18px; color: Var ws =new WebSocket("ws://127.0.0.1:8899/ws") # e51C23 "></div> <script type="application/javascript"> ws.onmessage = function (data){ console.log(data); var ptag = document.createElement("p"); ptag.innerText =data.data; document.getElementById("mesg").appendChild(ptag) } function send_msg(){ var msg = document.getElementById("inputmsg").value; ws.send(msg) } </script>Copy the code
Back-end code
from flask import Flask,render_template,request from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi The import WSGIServer from geventwebsocket. Websocket import websocket import pprint app = Flask (__name__) # to save the user added to the user list user_socket_list =[] @app.route("/ws") def ws(): try: user_socket = request.environ.get("wsgi.websocket") # type:WebSocket user_socket_list.append(user_socket) Print (user_socket_list) print(" Current user: %d"%len(user_socket_list)) if user_socket: # print(user_socket) # print(type(user_socket)) while True: msg =user_socket.receive() for user in user_socket_list: Try: user.send(" user [%s] : %s"%(user, MSG)) except: print(" user does not exist ") continue print(MSG) except: print(" connection failed!! ") ) return @app.route("/") def index(): return render_template("ws.html") # Flask if __name__ == '__main__': # app.run(debug=False) http_serv = WSGIServer(("0.0.0.0", 8899), app, handler_class=WebSocketHandler) http_serv.serve_forever()Copy the code