基于Flask的websocket实现用例
一个简单的websocket实现用例,实现多人聊天和私聊,直接上代码
1 import json 2 3 from flask import Flask,request,render_template 4 5 from geventwebsocket.handler import WebSocketHandler 6 from gevent.pywsgi import WSGIServer 7 from geventwebsocket.websocket import WebSocket 8 9 app = Flask(__name__) 10 11 user_socket_dict = {} 12 13 @app.route("/conn_ws/<user_nick>") 14 def ws_app(user_nick): 15 16 user_socket = request.environ.get("wsgi.websocket") # type:WebSocket 17 user_socket_dict[user_nick] = user_socket 18 print(len(user_socket_dict),list(user_socket_dict.keys())) 19 20 while True: 21 msg = user_socket.receive() 22 # {from_user:"用户",to_user:"收消息用户",message:"666"} 23 msg_dict = json.loads(msg) 24 to_user = msg_dict.get("to_user") 25 if to_user: 26 to_user_socket = user_socket_dict.get(to_user) 27 to_user_socket.send(msg) 28 else: 29 for user in user_socket_dict.values(): 30 user.send(msg) 31 32 33 @app.route("/") 34 def index(): 35 return render_template("my_ws.html") 36 37 38 if __name__ == '__main__': 39 # app.run() 40 http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) 41 http_serv.serve_forever()
前端页面需要有个websocket对象进行接收发送
<script type="application/javascript"> var ws = null; // ws.onopen = function(){ // ws.send("123"); // } function login() { var nick = document.getElementById("nick").value; ws = new WebSocket("ws://192.168.11.29:9527/conn_ws/"+nick); ws.onmessage = function (messageEvent) { console.log(messageEvent.data); var ptag = document.createElement("p"); var message = JSON.parse(messageEvent.data); ptag.innerText =message.from_user + " : " + message.message ; document.getElementById("chat_list").appendChild(ptag); }; } // document.getElementById("send_btn").addEventListener("onclick",) function send() { var message = document.getElementById("send_str").value; var send_str = { from_user:document.getElementById("nick").value, to_user:document.getElementById("to_user").value, message:message }; var json_send_str = JSON.stringify(send_str); ws.send(json_send_str); } </script>