简单理解WebSocket:因为 HTTP 协议有一个缺陷----通信只能由客户端发起。而WebSocket的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。
WebSocket模板
import json 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_dict = {} @app.route("/conn_ws/<user_nick>") def ws_app(user_nick): user_socket = request.environ.get("wsgi.websocket") # type:WebSocket user_socket_dict[user_nick] = user_socket print(len(user_socket_dict),list(user_socket_dict.keys())) while True: msg = user_socket.receive() # {from_user:"alexDSB",to_user:"YWB",message:"666"} 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) # # for usocket in user_socket_list: # usocket.send(msg) # user_socket.send(msg) if __name__ == '__main__': http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) http_serv.serve_forever()