python —— gevent详解(四)——项目实际应用

python —— gevent详解(四)——项目实际应用,第1张

概述三种通信模型简述:(1)轮询:客户端周期性不间断高频率的给服务器发送请求:客户端请求–服务器响应–断开连接,请求次数QPS比较频繁,对客户端和服务器的配置要求比较高(2)长轮询:客户端周期性不间断的给服务器发送请求:客户端与服务器建立的连接会保持一定时间,因此请求相对不会 三种通信模型简述:

(1)轮询:
客户端周期性不间断高频率的给服务器发送请求:
客户端请求–服务器响应–断开连接,请求次数QPS比较频繁,对客户端和服务器的配置要求比较高
(2)长轮询:
客户端周期性不间断的给服务器发送请求:
客户端与服务器建立的连接会保持一定时间,因此请求相对不会特别频繁
(3)长连接:
客户端与服务端建立连接后,如果不是特殊原因(客户端主动断开,服务器故障)连接会一直保持
同时通过多线程进行IO多路复用技术解决并发问题

flask中基于gevent-websocket的IO多路复用技术进行长连接通信:
(1)基于gevent-websocket的IO多路复用长连接通信,需要导入一下模块:

#pip install gevent-websocket导入IO多路复用模块        from geventwebsocket.handler import WebSocketHandler         #提供WS(websocket)协议处理        from geventwebsocket.server import WsgiServer                #websocket服务承载        #WsgiServer导入的就是gevent.pywsgi中的类        # from gevent.pywsgi import WsgiServer        from geventwebsocket.websocket import WebSocket              #websocket语法提示

(2)路由视图函数中的处理必须通过request.environ.get(‘wsgi.websocket’)获取与客户端的ws连接clIEnt_socket

#websocket协议通信如下(http请求正常处理即可)        @app.route()        def func():            clIEnt_socket=request.environ.get('wsgi.websocket')            while 1:                clIEnt_socket.recive()                    ...                clIEnt_socket.send(str)                    ...

(3)flask项目启动如下:

WsgiServer默认处理的是http请求,路由视图中可以正常使用http,
但是在使用ws协议时务必在视图函数通过request.environ.get(‘wsgi.websocket’)获取与客户端的ws连接clIEnt_socket,
通过连接clIEnt_socket进行clIEnt_socket.recive()/clIEnt_socket.send()通信,这连个方法会对字符串自动进行编解码)

http_server=WsgiServer(('192.168.16.14',8888),application=app,handler_class=WebSocketHandler。http_server.serve_forever()

(4)前端页面使用Js进行WS(websocket)请求:

浏览器提供了websocket客户端,直接new创建websocket连接ws,(ws状态码0表示已创建未连接,1表示已连接保持中,2表示客户端主动断开连接,3表示服务端断开连接),通过ws.onmessage=function (MessageEvent){}监听执行回调函数获取信息MessageEvent.data, 通过ws.send()发送信息。

<script>    var ws = new WebSocket('ws://192.168.16.14:8888/websocket');    ws.onmessage = function (MessageEvent) {        console.log(MessageEvent);        console.log(MessageEvent.data);            };    function send() {        var msg = document.getElementByID('msg').value;        ws.send(msg);    }</script>

http请求协议和websocket请求协议的请求原数据request.environ和请求头部信息request.headers比较:
http-environ:

{     'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6',      'SCRIPT_name': '', 'wsgi.version': (1, 0),      'wsgi.multithread': False, 'wsgi.multiprocess': False,      'wsgi.run_once': False, 'wsgi.url_scheme': 'http',      'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' enCoding='UTF-8'>,      'SERVER_name': 'PC-Yang', 'SERVER_PORT': '8888', 'REQUEST_METHOD': 'GET',     'PATH_INFO': '/websocket', 'query_STRING': '', 'SERVER_PROTOCol': 'http/1.1',     'REMOTE_ADDR': '192.168.16.14', 'REMOTE_PORT': '61539', 'http_HOST': '192.168.16.14:8888',     'http_CONNECTION': 'keep-alive', 'http_PRAGMA': 'no-cache', 'http_CACHE_CONTRol': 'no-cache',     'http_UPGRADE_INSECURE_REQUESTS': '1',     'http_USER_AGENT': 'Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',     'http_ACCEPT': 'text/HTML,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',     'http_ACCEPT_ENCoding': 'gzip, deflate', 'http_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9',     'wsgi.input': <gevent.pywsgi.input object at 0x03A9DC00>,      'wsgi.input_terminated': True, 'werkzeug.request': <Request 'http://192.168.16.14:8888/websocket' [GET]>    }

http-headers:

'''    Host: 192.168.16.14:8888    Connection: keep-alive    Pragma: no-cache    Cache-Control: no-cache    upgrade-insecure-requests: 1    User-Agent: Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36    Accept: text/HTML,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3    Accept-EnCoding: gzip, deflate    Accept-Language: zh-CN,zh;q=0.9

websocket-environ: ‘wsgi.websocket’: <geventwebsocket.websocket.WebSocket object at 0x03A9DC00>,websocket连接

'''    {     'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6',      'SCRIPT_name': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False,      'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http',      'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' enCoding='UTF-8'>,      'SERVER_name': 'PC-Yang', 'SERVER_PORT': '8888', 'REQUEST_METHOD': 'GET',     'PATH_INFO': '/websocket', 'query_STRING': '', 'SERVER_PROTOCol': 'http/1.1',     'REMOTE_ADDR': '192.168.16.14', 'REMOTE_PORT': '61591', 'http_HOST': '192.168.16.14:8888',     'http_CONNECTION': 'Upgrade', 'http_PRAGMA': 'no-cache', 'http_CACHE_CONTRol': 'no-cache',     'http_USER_AGENT': 'Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',     'http_UPGRADE': 'websocket', 'http_ORIGIN': 'http://192.168.16.14:8888', 'http_SEC_WEBSOCKET_VERSION': '13',     'http_ACCEPT_ENCoding': 'gzip, deflate', 'http_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9',     'http_SEC_WEBSOCKET_KEY': 'Oyfq0MCEBnsypKstjjRvYg==',     'http_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; clIEnt_max_window_bits',     'wsgi.input': <gevent.pywsgi.input object at 0x03A9DCA8>,     'wsgi.input_terminated': True, 'wsgi.websocket_version': '13',         'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x03A9DC00>,         'werkzeug.request': <Request 'http://192.168.16.14:8888/websocket' [GET]>    }'''

websocket-headers: Upgrade: websocket #websocket请求中的标识

'''    Host: 192.168.16.14:8888    Connection: Upgrade    Pragma: no-cache    Cache-Control: no-cache    User-Agent: Mozilla/5.0 (windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36        Upgrade: websocket   #websocket请求中的标识        Origin: http://192.168.16.14:8888    Sec-Websocket-Version: 13    Accept-EnCoding: gzip, deflate    Accept-Language: zh-CN,zh;q=0.9    Sec-Websocket-Key: Oyfq0MCEBnsypKstjjRvYg==    Sec-Websocket-Extensions: permessage-deflate; clIEnt_max_window_bits'''websocket-headers

(1)基于websocket+flask实现的群聊无昵称即时通信

flask_websocket(MUC_Nonick).py

1 ''' 2 基于websocket+flask实现的群聊无昵称即时通信 3 设计列表clIEnt_List = []来存储客户端与服务器的连接, 4 服务收到任意客户端的信息(信息时),对连接存储列表进行遍历获取每个连接,直接进行转发 5 ''' 6 from flask import Flask, render_template, request 7  8 # pip install gevent-websocket导入IO多路复用模块 9 from geventwebsocket.handler import WebSocketHandler  # 提供WS(websocket)协议处理10 from geventwebsocket.server import WsgiServer  # websocket服务承载11 # WsgiServer导入的就是gevent.pywsgi中的类12 # from gevent.pywsgi import WsgiServer13 from geventwebsocket.websocket import WebSocket  # websocket语法提示14 15 app = Flask(__name__)16 17 # @app.route('/websocket')18 # 多个客户端可以同时给falsk服务端发送ws协议的信息19 # def websocket():20 #     clIEnt_socket=request.environ.get('wsgi.websocket') #type:WebSocket21 #     while 1:22 #             msg_from_cli=clIEnt_socket.receive()23 #             print(msg_from_cli)24 # 多个客户端可以同时给falsk服务端发送ws协议的信息,同时服务端将信息转送到每个客户端页面,实现多人聊天室即时通信25 clIEnt_List = []26 27 28 @app.route('/websocket')29 def websocket():30     clIEnt_socket = request.environ.get('wsgi.websocket')  # type:WebSocket31     clIEnt_List.append(clIEnt_socket)32     # print(len(clIEnt_List), clIEnt_List)33     while 1:34         msg_from_cli = clIEnt_socket.receive()35         # print(msg_from_cli)36         #收到任何一个客户端的信息都进行全部转发(注意如果某个客户端连接断开,在遍历发送时连接不存在会报错,需要异常处理)37         for clIEnt in clIEnt_List:38             try:39                 clIEnt.send(msg_from_cli)40             except Exception as e:41                 continue42 43 @app.route('/chat')44 def chat():45     return render_template('MUC_Nonick.HTML')46 47 48 if __name__ == '__main__':49     # app.run('192.168.16.14',8888,deBUG=True)50     http_server = WsgiServer(('192.168.16.14', 8888), application=app, handler_class=WebSocketHandler)51     http_server.serve_forever()flask_websocket(MUC_Nonick).py

MUC_Nonick.HTML

1 <!DOCTYPE HTML> 2 <HTML lang="en"> 3 <head> 4     <Meta charset="UTF-8"> 5     <Title>多用户聊天无昵称</Title> 6 </head> 7 <body> 8 <div ID="chat_room"> 9     <p>请输入聊天内容:<input type="text" ID="msg">10         <button ID="send" onclick="send()">发送</button>11     </p>12     <div ID="chat_content"></div>13 </div>14 </body>15 <script type="application/JavaScript">16     var ws = new WebSocket('ws://192.168.16.14:8888/websocket');17     ws.onmessage = function (MessageEvent) {18         //console.log(MessageEvent);19        //console.log(MessageEvent.data);20         var time=new Date();21         var t= time.tolocaleString();22         var p=document.createElement("p");23         p.innerText="("+t+")"+MessageEvent.data;24         document.getElementByID('chat_content').appendChild(p);25     };26 27     function send() {28         var msg = document.getElementByID('msg').value;29         ws.send(msg);30     }31 </script>32 </HTML>MUC_Nonick.HTML

(2)基于websocket+flask实现的群聊有昵称即时通信

版本一:通过动态路有参数获取客户端昵称:

flask_websocket(MUC_nick_route).py

1 ''' 2 基于websocket+flask实现的群聊即时通信 3 设计字典clIEnt_dict = {}来存储{客户端的名字:客户端与服务器的连接},客户端的名字通过动态路由参数获取到, 4 服务器接收客户端发来的信息(经过Json序列化后的字典),对存储连接信息的字典进行遍历,获取客户端的连接,直接转发 5 ''' 6 from flask import Flask, render_template, request 7 from geventwebsocket.handler import WebSocketHandler  # 提供WS(websocket)协议处理 8 from geventwebsocket.server import WsgiServer  # websocket服务承载 9 from geventwebsocket.websocket import WebSocket  # websocket语法提示10 11 app = Flask(__name__)12 13 clIEnt_dict = {}14 15 16 @app.route('/websocket/<clIEnt_name>')#通过动态路由参数获取昵称,必须在视图函定义同名形参接收17 def websocket(clIEnt_name):18     clIEnt_socket = request.environ.get('wsgi.websocket')  # type:WebSocket19     clIEnt_dict[clIEnt_name] = clIEnt_socket20     # print(len(clIEnt_dict), clIEnt_dict)21     while 1:22         msg_from_cli = clIEnt_socket.receive()23         for clIEnt in clIEnt_dict.values():24             try:25                 clIEnt.send(msg_from_cli)26             except Exception as e:27                 continue28 29 30 @app.route('/chat')31 def chat():32     return render_template('MUC_nick_route.HTML')33 34 35 if __name__ == '__main__':36     # app.run('192.168.16.14',8888,deBUG=True)37     http_server = WsgiServer(('192.168.16.14', 8888), application=app, handler_class=WebSocketHandler)38     http_server.serve_forever()flask_websocket(MUC_nick_route).py

MUC_nick_route.HTML

1 <!DOCTYPE HTML> 2 <HTML lang="en"> 3 <head> 4     <Meta charset="UTF-8"> 5     <Title>多用户聊天无昵称</Title> 6 </head> 7 <body> 8 <div ID="chat_room"> 9     <p>输入昵称进入多人聊天室:<input type="text" ID="clIEnt_name"></input>10         <button ID='login' onclick="login()">登录</button>11     </p>12     <p ID='chat_msg' hIDden="hIDden">请输入聊天内容:<input type="text" ID="msg">13         <button ID="send" onclick="send()">发送</button>14     </p>15     <div ID="chat_content" hIDden="hIDden"></div>16 </div>17 </body>18 <script type="application/JavaScript">19     var ws = null;20     var name=null;21 22     function login() {23         document.getElementByID('login').setAttribute('hIDden', 'hIDden');24         document.getElementByID('clIEnt_name').setAttribute('Disabled', 'Disabled');25         document.getElementByID('chat_msg').removeAttribute('hIDden');26         document.getElementByID('chat_content').removeAttribute('hIDden');27         name = document.getElementByID('clIEnt_name').value;28         //进行WS实例化29         ws = new WebSocket('ws://192.168.16.14:8888/websocket/' + name);30 31         //监听服务器发来的消息(Json数据)32         ws.onmessage = function (MessageEvent) {33             //console.log(MessageEvent);34             //console.log(MessageEvent.data);35             var content_str = JsON.parse(MessageEvent.data);36             var time = new Date();37             var t = time.tolocaleTimeString();38             var p = document.createElement("p");39             p.innerText = content_str.name + "(" + t + "):" + content_str.msg;40             document.getElementByID('chat_content').appendChild(p);41         };42     };43 44 45     //聊天信息发送(Json数据)46     function send() {47         var msg = document.getElementByID('msg').value;48         var data = {49             name: name,50             msg: msg,51         };52         var data_Json = JsON.stringify(data);53         ws.send(data_Json);54     }55 </script>56 </HTML>MUC_nick_route.HTML

版本二:通过websocket接收客户端发来基于websocket发来的昵称:

flask_websocket(MUC_nick).py

1 ''' 2 基于websocket+flask实现的群聊即时通信 3 设计字典clIEnt_dict = {}来存储{客户端的名字:客户端与服务器的连接},客户端的名字通过客户端执行WS请求协议发送获取, 4 服务器再持续接收客户端发来的信息(经过Json序列化后的字典),对存储连接信息的字典进行遍历,获取客户端的连接,直接转发 5 ''' 6 from flask import Flask, render_template, request 7 from geventwebsocket.handler import WebSocketHandler  # 提供WS(websocket)协议处理 8 from geventwebsocket.server import WsgiServer  # websocket服务承载 9 from geventwebsocket.websocket import WebSocket  # websocket语法提示10 11 12 app = Flask(__name__)13 14 clIEnt_dict = {}15 16 17 @app.route('/websocket')18 def websocket():19     clIEnt_socket = request.environ.get('wsgi.websocket')  # type:WebSocket20     # print(clIEnt_socket)21     clIEnt_name = clIEnt_socket.receive()22     clIEnt_dict[clIEnt_name] = clIEnt_socket23     # print(len(clIEnt_dict), clIEnt_dict)24     while 1:25         msg_from_cli = clIEnt_socket.receive()26         # msg_from_cli_str=Json.loads(msg_from_cli)27         # print(msg_from_cli_str)28         for clIEnt in clIEnt_dict.values():29             try:30                 clIEnt.send(msg_from_cli)31             except Exception as e:32                 continue33 34 35 @app.route('/chat')36 def chat():37     return render_template('MUC_nick.HTML')38 39 40 if __name__ == '__main__':41     # app.run('192.168.16.14',8888,deBUG=True)42     http_server = WsgiServer(('192.168.16.14', 8888), application=app, handler_class=WebSocketHandler)43     http_server.serve_forever()flask_websocket(MUC_nick).py

MUC_nick.HTML

1 <!DOCTYPE HTML> 2 <HTML lang="en"> 3 <head> 4     <Meta charset="UTF-8"> 5     <Title>多用户聊天无昵称</Title> 6 </head> 7 <body> 8 <div ID="chat_room"> 9     <p>输入昵称进入多人聊天室:<input type="text" ID="clIEnt_name"></input>10         <button ID='login' onclick="login()">登录</button>11     </p>12     <p ID='chat_msg' hIDden="hIDden">请输入聊天内容:<input type="text" ID="msg">13         <button ID="send" onclick="send()">发送</button>14     </p>15     <div ID="chat_content" ></div>16 </div>17 </body>18 <script type="application/JavaScript">19     var ws = new WebSocket('ws://192.168.16.14:8888/websocket');20     var name = null;21 22     //向服务端发送本机昵称23     function login() {24         document.getElementByID('login').setAttribute('hIDden', 'hIDden');25         document.getElementByID('clIEnt_name').setAttribute('Disabled', 'Disabled');26         document.getElementByID('chat_msg').removeAttribute('hIDden');27         document.getElementByID('chat_content').removeAttribute('hIDden');28         name = document.getElementByID('clIEnt_name').value;29         ws.send(name);30     };31 32 33    //监听服务器发来的消息(Json数据)34     ws.onmessage = function (MessageEvent) {35         //console.log(MessageEvent);36         //console.log(MessageEvent.data);37         var content_str = JsON.parse(MessageEvent.data);38         var time = new Date();39         var t = time.tolocaleTimeString();40         var p = document.createElement("p");41         p.innerText = content_str.name + "(" + t + "):" + content_str.msg;42         document.getElementByID('chat_content').appendChild(p);43     };44 45 46     //聊天信息发送(Json数据)47     function send() {48         var msg = document.getElementByID('msg').value;49         var data = {50             name: name,51             msg: msg52         };53         var data_Json = JsON.stringify(data);54         ws.send(data_Json);55     }56 </script>57 </HTML>MUC_nick.HTML

(3)基于websocket+flask实现的私聊即时通信

flask_websocket(Private_chat).py

1 ''' 2 基于websocket+flask实现的私聊即时通信 3 设计字典clIEnt_dict = {}来存储{客户端的名字:客户端与服务器的连接},客户端的名字通过动态路由参数获取到, 4 服务器通过客户端发来的信息(经过Json序列化后的字典)中的目标客户端名字,在存储字典中获取目标客户端的连接,直接转发 5 ''' 6 from flask import Flask, render_template, request 7 from geventwebsocket.handler import WebSocketHandler  # 提供WS(websocket)协议处理 8 from geventwebsocket.server import WsgiServer  # websocket服务承载 9 from geventwebsocket.websocket import WebSocket  # websocket语法提示10 import Json11 12 app = Flask(__name__)13 14 clIEnt_dict = {}15 16 17 @app.route('/websocket/<clIEnt_name>')  # 通过动态路由参数获取昵称,必须在视图函定义同名形参接收18 def websocket(clIEnt_name):19     clIEnt_socket = request.environ.get('wsgi.websocket')  # type:WebSocket20     clIEnt_dict[clIEnt_name] = clIEnt_socket21     if clIEnt_socket:22         while 1:23             msg_from_cli = clIEnt_socket.receive()24             to_clIEnt = Json.loads(msg_from_cli).get('to_clIEnt')25             clIEnt = clIEnt_dict.get(to_clIEnt)26             try:27                 clIEnt.send(msg_from_cli)28             except Exception as e:29                 continue30 31 32 @app.route('/chat')33 def chat():34     return render_template('Private_chat.HTML')35 36 37 if __name__ == '__main__':38     http_server = WsgiServer(('192.168.16.14', 8888), application=app, handler_class=WebSocketHandler)39     http_server.serve_forever()flask_websocket(Private_chat).py

Private_chat.HTML

1 <!DOCTYPE HTML> 2 <HTML lang="en"> 3 <head> 4     <Meta charset="UTF-8"> 5     <Title>单人聊天室</Title> 6  7 </head> 8 <body> 9 <div ID="chat_room">10     <p>输入昵称进入单人聊天室:<input type="text" ID="clIEnt_name"></input>11         <button ID='login' onclick="login()">登录</button>12     </p>13     <p hIDden ID="clIEnt_recv">收信人:<input type="text" ID="to_clIEnt"></p>14     <p ID='chat_msg' hIDden="hIDden">请输入聊天内容:<input type="text" ID="msg">15 16         <button ID="send" onclick="send()">发送</button>17     </p>18     <div ID="chat_content" hIDden="hIDden"></div>19 </div>20 </body>21 <script type="application/JavaScript">22     var ws = null;23     var name=null;24 25     function login() {26         document.getElementByID('login').setAttribute('hIDden', 'hIDden');27         document.getElementByID('clIEnt_name').setAttribute('Disabled', 'Disabled');28         document.getElementByID('chat_msg').removeAttribute('hIDden');29         document.getElementByID('chat_content').removeAttribute('hIDden');30         document.getElementByID('clIEnt_recv').removeAttribute('hIDden');31 32         name = document.getElementByID('clIEnt_name').value;33         //进行WS实例化34         ws = new WebSocket('ws://192.168.16.14:8888/websocket/' + name);35 36         //监听服务器发来的消息(Json数据)37         ws.onmessage = function (MessageEvent) {38             //console.log(MessageEvent);39             //console.log(MessageEvent.data);40             var content_str = JsON.parse(MessageEvent.data);41             var time = new Date();42             var t = time.tolocaleTimeString();43             var p = document.createElement("p");44             p.innerText = content_str.name + "(" + t + "):" + content_str.msg;45             document.getElementByID('chat_content').appendChild(p);46         };47     };48 49 50     //聊天信息发送(Json数据)51     function send() {52         var msg = document.getElementByID('msg').value;53         var to_clIEnt=document.getElementByID('to_clIEnt').value;54         var data = {55             name: name,56             msg: msg,57             to_clIEnt:to_clIEnt58         };59 60         var data_Json = JsON.stringify(data);61         ws.send(data_Json);62 63 64         var time = new Date();65             var t = time.tolocaleTimeString();66             var p = document.createElement("p");67             p.innerText = name + "(" + t + "):" + msg;68             document.getElementByID('chat_content').appendChild(p);69 70 71 72 73 74     }75 </script>76 </HTML>Private_chat.HTML
实际项目后台代码:
#! /usr/bin/python2#! -*- Coding:utf-8  -*-from flask import Flask,requestfrom gevent import monkeyfrom gevent.pywsgi import WsgiServerfrom geventwebsocket.handler import WebSocketHandlerimport timeimport Jsonimport sysimport tracebackimport loggingfrom InteractiveWithDatabase.interactive_with_database import Get_first_record_from_databasefrom pub.const_redis import SYstem_KEY_namefrom MEO_DB import redislifecyclemonkey.patch_all()  #支持异步请求app = Flask(__name__)app.config.update(    DEBUG=True)logger = logging.getLogger('eb_meo')@app.route("/conn_vnfm")def ws_app():    user_socket = request.environ.get("wsgi.websocket")    sys_ID = user_socket.receive()    subsDb = Get_first_record_from_database('Alarm_subscription', system_ID=sys_ID)    try:        if subsDb:            SrcType = subsDb.sub_type            while True:                if redislifecycle.get(SYstem_KEY_name.HeartBeat + SrcType.lower() + '_' + sys_ID):                    user_socket.send(Json.dumps({sys_ID:True}))                else:                    user_socket.send(Json.dumps({sys_ID:False}))                time.sleep(subsDb.heartbeat)        else:            user_socket.send(Json.dumps({sys_ID:False}))    except:        logger.deBUG(sys.exc_info())        logger.deBUG(traceback.format_exc())    return ''# 服务器端没关闭之前必须有接收阻塞,否则服务器和客户端都会死循环而崩溃# websocket的原理:客户端发送消息请求,服务器端回复数据【客户端不发消息,循环不会阻塞就是死循环】if __name__ == '__main__':    http_serv=WsgiServer(("0.0.0.0",int(sys.argv[1])),app,handler_class=WebSocketHandler)    http_serv.serve_forever()
实际项目前端处理:
{% block scripts %}{{super()}}<script type="text/JavaScript" src="{{url_for('static',filename = 'Js/system.Js')}}"></script><script>    //接入系统连接状态持续监控功能    var web_socket_msg = {{exTradata|toJson}}    console.log(web_socket_msg)    var vnfms = {{resData.vnfms|toJson}}    function con_svr(vnfm_ID){         // 协议为ws,和http配合 wws,和httpS配合使用        let ws = new WebSocket('ws://' + web_socket_msg.ip + ':' + String(web_socket_msg.port) + '/conn_vnfm')        ws.onopen = function (params) {          console.log(vnfm_ID + '连接成功')          ws.send(vnfm_ID)        }        ws.onmessage = function (e) {          console.log(vnfm_ID + '收到服务器响应', e.data)          var res = JsON.parse(e.data)          if (res[vnfm_ID]){              $('#status-' + vnfm_ID).addClass('glyphicon-ok-sign').CSS('color','#5CCBB1')          }else{              $('#status-' + vnfm_ID).removeClass('glyphicon-ok-sign').CSS('color','#E54545')          }        }    }    for (let vnfm of vnfms){        con_svr(vnfm.vnfm_ID)    }</script>{% endblock %}
总结

以上是内存溢出为你收集整理的python —— gevent详解(四)——项目实际应用全部内容,希望文章能够帮你解决python —— gevent详解(四)——项目实际应用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1186450.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存