1.多人聊天
from geventwebsocket.handler import WebSocketHandler # 请求处理WSGI HTTP from geventwebsocket.server import WSGIServer # 替换Flask原来的WSGI服务 from geventwebsocket.websocket import WebSocket # 语法提示 from flask import Flask, render_template, request app = Flask(__name__) socket_dict = {} @app.route("/ws") def my_ws(): ws_socket = request.environ.get("wsgi.websocket")# type:WebSocket socket_dict[ws_socket] = ws_socket # 可以使用用户名,使用动态路由参数传username print(socket_dict) while True: msg = ws_socket.receive() print(msg) for ksocket,vscoket in socket_dict.items(): if ksocket == ws_socket: continue vscoket.send(msg) @app.route("/wechat") def wechat(): return render_template("测试用.html") if __name__ == "__main__": http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler) # WebSocketHandler既支持websocket请求,也支持http请求 http_serv.serve_forever() # wsgi启动服务
<!DOCTYPE html> <html lang="en"> <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> body #content_list { border: solid black; 400px; height: 400px; } </style> </head> <body> <div id="content_list" style="overflow-y: auto"></div> <p> 昵称:<input type="text" id="username"> <button onclick="login()">登录聊天室</button> </p> <input type="text" id="content"> <button onclick="send_msg()">发送消息</button> </body> <script type="application/javascript"> var ws = null; function send_msg() { var msg = document.getElementById("content").value; //获取发送内容 var sender = document.getElementById("username").value; //获取发送人名字 // 发送的信息内容 var send_str = { sender: sender, data: msg }; ws.send(JSON.stringify(send_str)); // 将发送的信息json序列化 var my_div = document.getElementById("content_list"); // 获取div标签 var ptag = document.createElement("p"); // 创建一个p标签 ptag.innerText = msg + " : 我"; // 设置p标签中的文本内容 ptag.style.cssText = "text-align: right"; // p标签设置css样式,文本靠右 my_div.appendChild(ptag); // 将p标签添加进div标签中 document.getElementById("content").value = ""; } function login() { var username = document.getElementById("username").value; // 获取登录用户名 console.log(username); ws = new WebSocket("ws://127.0.0.1:9527/ws"); // 执行websocket服务,如果需要username,可以在url上增加 // 当客户端收到消息时,执行匿名函数 ws.onmessage = function (messageEvent) { console.log(messageEvent.data); var obj = JSON.parse(messageEvent.data); // 将接收的数据反序列化 var my_div = document.getElementById("content_list"); // 获取div标签 var ptag = document.createElement("p"); // 获取p标签 ptag.innerText = obj.sender + " : " + obj.data; // 设置p标签中文本内容 my_div.appendChild(ptag); // 将p标签放到div中 }; } </script> </html>
2.一对一聊天
import json from geventwebsocket.handler import WebSocketHandler # 请求处理WSGI HTTP from geventwebsocket.server import WSGIServer # 替换Flask原来的WSGI服务 from geventwebsocket.websocket import WebSocket # 语法提示 from flask import Flask,render_template,request app = Flask(__name__) socket_dict = {} @app.route("/ws/<username>") def my_ws(username): # 获取链接地址 ws_socket = request.environ.get("wsgi.websocket") #type:WebSocket socket_dict[username] = ws_socket while True: msg = ws_socket.receive() # 接收浏览器发来的信息 msg_dict = json.loads(msg) # 将信息反序列化,是字典 receiver = msg_dict.get("receiver") # 获取字典中接收人的名字 receiver_socket = socket_dict.get(receiver) # 从字典中找到接收人名字对应的链接地址 receiver_socket.send(msg) # 向接收人的链接地址发送信息 @app.route("/wechat") def wechat(): return render_template("测试用.html") if __name__ == "__main__": http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) # WebSocketHandler既支持websocket请求,也支持http请求 http_serv.serve_forever() # wsgi启动服务
<!DOCTYPE html> <html lang="en"> <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> body #content_list { border: solid black; 400px; height: 400px; } </style> </head> <body> <div id="content_list" style="overflow-y: auto"></div> <p> 昵称:<input type="text" id="username"> <button onclick="login()">登录聊天室</button> </p> 给<input type="text" id="receiver">发送<input type="text" id="content"> <button onclick="send_msg()">发送消息</button> </body> <script type="application/javascript"> var ws = null; function send_msg() { var msg = document.getElementById("content").value; //获取发送内容 var receiver = document.getElementById("receiver").value; // 获取接收人名字 var sender = document.getElementById("username").value; //获取发送人名字 // 发送的信息内容 var send_str = { receiver: receiver, sender: sender, data: msg }; ws.send(JSON.stringify(send_str)); // 将发送的信息json序列化 var my_div = document.getElementById("content_list"); // 获取div标签 var ptag = document.createElement("p"); // 创建一个p标签 ptag.innerText = msg + " : 我"; // 设置p标签中的文本内容 ptag.style.cssText = "text-align: right"; // p标签设置css样式,文本靠右 my_div.appendChild(ptag); // 将p标签添加进div标签中 document.getElementById("content").value = ""; //将聊天输入框置空 } function login() { var username = document.getElementById("username").value; // 获取登录用户名 ws = new WebSocket("ws://127.0.0.1:9527/ws/" + username); // 执行websocket服务 // 当客户端收到消息时,执行匿名函数 ws.onmessage = function (messageEvent) { console.log(messageEvent.data); var obj = JSON.parse(messageEvent.data); // 将接收的数据反序列化 var my_div = document.getElementById("content_list"); // 获取div标签 var ptag = document.createElement("p"); // 获取p标签 ptag.innerText = obj.sender + " : " + obj.data; // 设置p标签中文本内容 my_div.appendChild(ptag); // 将p标签放到div中 }; } </script> </html>