使用websocket实现单聊和多聊
单聊:
前端:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" 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> </head> <body> <p>您的昵称:<input type="text" id="nick"><button onclick="openws()">进入聊天室</button></p> <p>给<input type="text" id="to_user">发送:<input type="text" id="message"><button onclick="send_msg()">发送消息</button></p> <div id="msg_list" style="width: 500px;"> </div> </body> <script type="application/javascript"> var ws = null; // ws.onopen = function(){ // alert("欢迎来到群喷"); // }; function openws(){ var nick = document.getElementById("nick").value; ws = new WebSocket("ws://192.168.12.10:5000/ws/"+nick); ws.onmessage = function (ws_status) { console.log(ws_status.data); var msg_obj = JSON.parse(ws_status.data); var ptag = document.createElement("p"); ptag.innerText = msg_obj.from_user + " : " +msg_obj.msg; document.getElementById("msg_list").appendChild(ptag); }; } function send_msg() { var msg = document.getElementById("message").value; var from_user = document.getElementById("nick").value; var to_user = document.getElementById("to_user").value; var ptag = document.createElement("p"); ptag.style.cssText = "text-align: right;"; ptag.innerText = msg + " : "+ from_user; document.getElementById("msg_list").appendChild(ptag); var msg_obj = { msg:msg, from_user:from_user, to_user:to_user }; ws.send(JSON.stringify(msg_obj)); }; </script> </html>
后端:
from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import json from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socket_dict = { } @app.route('/ws/<user>') def ws(user): user_socket = request.environ.get('wsgi.websocket') #原请求 if user_socket: user_socket_dict[user] = user_socket while 1: msg = user_socket.receive() msg_dict = json.loads(msg) to_usocket = user_socket_dict.get(msg_dict.get("to_user")) to_usocket.send(json.dumps({"from_user": user, "to_user": msg_dict.get("to_user"), "msg": msg_dict.get("msg")})) @app.route("/") def index(): return render_template("ws_one.html") if __name__ == '__main__': # app.run("0.0.0.0",5000,debug=True) http_serv = WSGIServer(("0.0.0.0", 5000), app, handler_class=WebSocketHandler) http_serv.serve_forever()
多聊:
前端
<!DOCTYPE html> <html lang="zn-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> </head> <body> <p>发送内容: <input type="text" id="message"> <button onclick="send_msg()">发送消息</button></p> <div id="msg_list" style="width: 500px"></div> </body> <script type="application/javascript"> var ws = new WebSocket("ws://192.168.12.10:5000/ws"); // ws.onopen = function(){ //当打开的时候发送消息 // ws.send('hello') // }; ws.onmessage = function (ws_status) { console.log(ws_status.data); var ptag = document.createElement('p'); ptag.innerText = ws_status.data; document.getElementById('msg_list').appendChild(ptag) }; function send_msg() { var msg = document.getElementById('message').value; var ptag = document.createElement('p'); ptag.style.cssText = 'text-align:right;'; ptag.innerText = msg; document.getElementById('msg_list').appendChild(ptag) ws.send(msg) } </script> </html>
后端:
from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socker_list = [] @app.route('/ws') def ws(): user_socker = request.environ.get('wsgi.websocket') #type:WebSocket if user_socker: user_socker_list.append(user_socker) print(len(user_socker_list), user_socker_list) while 1: msg = user_socker.receive() print(msg) for usocker in user_socker_list: if user_socker == usocker: continue try: usocker.send(msg) except: continue @app.route('/') def index(): return render_template('ws_all.html') if __name__ == '__main__': # app.run(debug=True) http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler) http_serv.serve_forever()