一 . WebSocket实现群聊
py文件代码
# py文件from flask import Flask, render_template, requestfrom geventwebsocket.handler import WebSocketHandlerfrom geventwebsocket.websocket import WebSocketfrom geventwebsocket.exceptions import WebSocketErrorfrom gevent.pywsgi import WSGIServer app = Flask(__name__)user_socket_list = []@app.route('/index')def index(): return render_template('index.html')@app.route('/my/ws')def my_ws(): # 当前端声明WebSocket的时候才有wsgi.websocket user_socket = request.environ.get('wsgi.websocket') # type:WebSocket # 为了让下面user_socket点的时候有提示 user_socket_list.append(user_socket) print(len(user_socket_list), user_socket_list) while 1: try: # 下面用图解释为什么要try msg = user_socket.receive() # 阻塞等待发送信息 except WebSocketError: user_socket_list.remove(user_socket) return 'GoodBye' for user in user_socket_list: if user == user_socket: continue try: user.send(msg) except: continueif __name__ == '__main__': # 用下面这种方法启动是为了识别并支持websocket http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler) http_server.serve_forever()
html代码
index
不try的时候
try之后
二 . 单聊
py文件
import jsonfrom flask import Flask, render_template, requestfrom geventwebsocket.handler import WebSocketHandlerfrom geventwebsocket.websocket import WebSocketfrom geventwebsocket.exceptions import WebSocketErrorfrom gevent.pywsgi import WSGIServerapp = Flask(__name__)user_socket_dict = {}@app.route('/home')def index(): return render_template('home.html')@app.route('/my/ws/')def my_ws(username): user_socket = request.environ.get('wsgi.websocket') # type:WebSocket user_socket_dict[username] = user_socket print(len(user_socket_dict), user_socket_dict) while 1: try: msg = user_socket.receive() # 阻塞等待消息 # print(msg, type(msg)) msg_dict = json.loads(msg) to_user = msg_dict.get('to_user') to_user_socket = user_socket_dict.get(to_user) to_user_socket.send(msg) except WebSocketError: user_socket_dict.pop(username) return 'GoodBye'if __name__ == '__main__': http_server = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler) http_server.serve_forever()
html文件
Title 发送者
接受者
消息
展示结果: