websocket 群聊
前提关闭防火墙
写入代码
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_socket_list=[] @app.route("/conn_ws") def ws_app(): # print(request.environ) """ wsgi.websocket:<geventwebsocket.websocket.WebSocket object at 0x0000000003Bc8528> :return: """ user_socket = request.environ.get("wsgi.websocket") user_socket_list.append(user_socket) while True: msg =user_socket.receive() print(msg) for usocket in user_socket_list: usocket.send(msg) #user_socket.send(msg) #1 已经开启的websocket连接 #3 开启了websocket连接 然后 断开了 # return "123" @app.route("/") def index(): return render_template("my_ws.html") if __name__ =="__main__": http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) http_serv.serve_forever()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="send_str"> <button id="send_btn" onclick="send()"> 发送消息</button> <p> <div id="chat_list"> </div> </p> </body> <script type="application/javascript"> var ws=new WebSocket("ws://192.168.11.78:9527/conn_ws"); // 自己的ip地址,页面才往自己页面显示内容 ws.onmessage =function (messageEvent) { console.log(messageEvent.data); var ptag = document.createElement("p"); ptag.innerText =messageEvent.data; document.getElementById("chat_list").appendChild(ptag); }; function send() { var send_str = document.getElementById("send_str").value; ws.send(send_str); } </script> </html>
这样就可以群聊了