1.前端HTML
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div style="width: 600px;"> <input type="text" id="username"> <button onclick="login()">登录聊天室</button> </div> <br> <div style="width: 600px;"> 给:<input type="text" id="to_user"> 发送:<input type="text" id="msg"> <button onclick="send_msg()">发送</button> </div> <br> <div id="chat_list" style="width: 600px;height: 300px;"></div> </body> <script type="application/javascript"> var ws = null; function login() { var username = document.getElementById("username").value; // 打印当前登录用户名 console.log(username); // 注意ws/,斜线不要忘记写 ws = new WebSocket("ws://192.168.13.21:5300/ws/" + username); // 打印创建的socket链接 console.log(ws); ws.onmessage = function (data) { console.log(data.data); var recv_msg = JSON.parse(data.data); var ptag = document.createElement("p"); ptag.innerText = recv_msg.from_user + ":" + recv_msg.msg; document.getElementById("chat_list").appendChild(ptag); } } function send_msg() { var to_user = document.getElementById("to_user").value; var msg = document.getElementById("msg").value; var send_str = { "to_user": to_user, "msg": msg }; ws.send(JSON.stringify(send_str)); } </script> </html>
2.后端PYTHON
from flask import Flask,render_template,request from geventwebsocket.handler import WebSocketHandler from geventwebsocket.websocket import WebSocket from gevent.pywsgi import WSGIServer import json app=Flask(__name__) user_socket_list = [] user_socket_dict = {} @app.route("/ws/<username>") def ws(username): print('当前登录账号:',username) user_socket = request.environ.get("wsgi.websocket") #type:WebSocket if user_socket: user_socket_dict[username] = user_socket else: pass while 1: msg = user_socket.receive() msg_dict = json.loads(msg) msg_dict["from_user"] = username to_user = msg_dict.get("to_user") u_socket = user_socket_dict.get(to_user) # type:WebSocket u_socket.send(json.dumps(msg_dict)) @app.route("/") def index(): return render_template("ws.html") if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0",5300),app,handler_class=WebSocketHandler) http_serv.serve_forever()
需要借助2个浏览器实现