websocket实现群聊
server # @File: 群聊 from flask import Flask, render_template, request from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket app = Flask(__name__) user_socket_list = [] @app.route('/ws') def ws(): # 一个用户的长链接wsgi.websocket user_socket = request.environ.get("wsgi.websocket") # type:WebSocket if user_socket: # 将每个链接存入列表中 user_socket_list.append(user_socket) print(len(user_socket_list), user_socket_list) while 1: msg = user_socket.receive() print(msg) for usocket in user_socket_list: if user_socket == usocket: continue try: usocket.send(msg) except: continue @app.route('/') def index(): return render_template("many_person.html") if __name__ == '__main__': http_server = WSGIServer(("0.0.0.0", 7000), app, handler_class=WebSocketHandler) http_server.serve_forever()
many_person.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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.41:7000/ws"); 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>