python -- detailed explanation of gevent -- practical application of the project

Brief description of three communication models:

(1) Polling:
The client sends requests to the server periodically and continuously at high frequency:
Client request - server response - disconnect. The number of requests QPS is relatively frequent, and the configuration requirements of client and server are relatively high
(2) Long polling:
The client sends requests to the server periodically and continuously:
The connection between the client and the server will be maintained for a certain period of time, so the requests will not be particularly frequent
(3) Long connection:
After the client establishes a connection with the server, if it is not for special reasons (the client actively disconnects and the server fails), the connection will remain
At the same time, IO multiplexing technology through multithreading is used to solve the concurrency problem

Long connection communication based on IO multiplexing technology of gevent websocket in flash:
(1) For IO multiplex long connection communication based on gevent websocket, the following modules need to be imported:

#PIP install gevent websocket import IO multiplexing module
        from geventwebsocket.handler import WebSocketHandler         #Provide WS (websocket) protocol processing
        from geventwebsocket.server import WSGIServer                #websocket service bearer
        #What WSGIServer imports is gevent Classes in pywsgi
        # from gevent.pywsgi import WSGIServer
        from geventwebsocket.websocket import WebSocket              #websocket syntax tips

(2) The processing in the routing view function must pass request environ. Get ('wsgi.websocket ') get the ws connection client with the client_socket:

#websocket protocol communication is as follows (http request can be processed normally)
        @app.route()
        def func():
            client_socket=request.environ.get('wsgi.websocket')
            while 1:
                client_socket.recive()
                    ...
                client_socket.send(str)
                    ...

(3) The launch of flash project is as follows:

WSGIServer processes http requests by default. http can be used normally in the routing view,
However, when using ws protocol, be sure to pass request. In the view function environ. Get ('wsgi.websocket ') get the ws connection client with the client_socket,
Connect client via_ Socket client_socket.recive()/client_socket.send() communication, which will automatically encode and decode the string)

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

(4) The front-end page uses js to make WS(websocket) requests:

The browser provides a websocket client and directly creates a websocket connection to ws through new (ws status code 0 indicates that the connection has been created but not connected, 1 indicates that the connection is still in progress, 2 indicates that the client actively disconnects, and 3 indicates that the server disconnects) Onmessage = function (messageevent) {} listen and execute callback function to get information messageevent Data, via ws Send() sends a message.

<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>

Request original data request of http request protocol and websocket request protocol Environ and request header information request Headers comparison:
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 connection

'''
    {
     '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: Identity in websocket #websocket request

'''
    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   #Identification in websocket request
    
    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) Group chat instant messaging without nickname based on websocket + Flash

flask_websocket(MUC_Nonick).py

1 '''
 2 be based on websocket+flask Group chat and nickname free instant messaging
 3 Design list client_list = []To store the connection between the client and the server,
 4 When the service receives information from any client (information), it traverses the connection storage list, obtains each connection, and forwards it directly
 5 '''
 6 from flask import Flask, render_template, request
 7 
 8 # PIP install gevent websocket import IO multiplexing module
 9 from geventwebsocket.handler import WebSocketHandler  # Provide WS (websocket) protocol processing
10 from geventwebsocket.server import WSGIServer  # websocket service bearer
11 # What WSGIServer imports is gevent Classes in pywsgi
12 # from gevent.pywsgi import WSGIServer
13 from geventwebsocket.websocket import WebSocket  # websocket syntax tips
14 
15 app = Flask(__name__)
16 
17 # @app.route('/websocket')
18 # Multiple clients can send ws protocol information to the false server at the same time
19 # def websocket():
20 #     client_socket=request.environ.get('wsgi.websocket') #type:WebSocket
21 #     while 1:
22 #             msg_from_cli=client_socket.receive()
23 #             print(msg_from_cli)
24 # Multiple clients can send ws protocol information to the false server at the same time, and the server forwards the information to each client page to realize instant messaging in the multi person chat room
25 client_list = []
26 
27 
28 @app.route('/websocket')
29 def websocket():
30     client_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
31     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         #All information received from any client will be forwarded (note that if a client is disconnected, an error will be reported when the connection does not exist during traversal and sending, and exception handling is required)
37         for client in client_list:
38             try:
39                 client.send(msg_from_cli)
40             except Exception as e:
41                 continue
42 
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>Multi user chat without nickname</title>
 6 </head>
 7 <body>
 8 <div id="chat_room">
 9     <p>Please enter chat content:<input type="text" id="msg">
10         <button id="send" onclick="send()">send out</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) Group chat instant messaging with nickname based on websocket + Flash

Version 1: obtain the nickname of the client through the dynamic path parameters:

flask_websocket(MUC_nick_route).py

1 '''
 2 be based on websocket+flask Group chat instant messaging
 3 Design dictionary client_dict = {}To store{Client Name: the connection between the client and the server},The name of the client is obtained through dynamic routing parameters,
 4 The server receives the information from the client (via json The serialized Dictionary) traverses the dictionary storing connection information, obtains the connection of the client and forwards it directly
 5 '''
 6 from flask import Flask, render_template, request
 7 from geventwebsocket.handler import WebSocketHandler  # Provide WS (websocket) protocol processing
 8 from geventwebsocket.server import WSGIServer  # websocket service bearer
 9 from geventwebsocket.websocket import WebSocket  # websocket syntax tips
10 
11 app = Flask(__name__)
12 
13 client_dict = {}
14 
15 
16 @app.route('/websocket/<client_name>')#To obtain nicknames through dynamic routing parameters, you must define a formal parameter with the same name in the view function
17 def websocket(client_name):
18     client_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
19     client_dict[client_name] = client_socket
20     # 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                 continue
28 
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>Multi user chat without nickname</title>
 6 </head>
 7 <body>
 8 <div id="chat_room">
 9     <p>Enter your nickname to enter the multiplayer chat room:<input type="text" id="client_name"></input>
10         <button id='login' onclick="login()">Sign in</button>
11     </p>
12     <p id='chat_msg' hidden="hidden">Please enter chat content:<input type="text" id="msg">
13         <button id="send" onclick="send()">send out</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 instantiation
29         ws = new WebSocket('ws://192.168.16.14:8888/websocket/' + name);
30 
31         //Listen for messages from the server (json data)
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     //Chat message sending (json data)
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

Version 2: receive the nickname sent by the client through websocket based on the nickname sent by websocket:

flask_websocket(MUC_nick).py

1 '''
 2 be based on websocket+flask Group chat instant messaging
 3 Design dictionary client_dict = {}To store{Client Name: the connection between the client and the server},The name of the client is executed by the client WS Request protocol sending and obtaining,
 4 The server continues to receive the information sent by the client (after json The serialized Dictionary) traverses the dictionary storing connection information, obtains the connection of the client and forwards it directly
 5 '''
 6 from flask import Flask, render_template, request
 7 from geventwebsocket.handler import WebSocketHandler  # Provide WS (websocket) protocol processing
 8 from geventwebsocket.server import WSGIServer  # websocket service bearer
 9 from geventwebsocket.websocket import WebSocket  # websocket syntax tips
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:WebSocket
20     # print(client_socket)
21     client_name = client_socket.receive()
22     client_dict[client_name] = client_socket
23     # 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                 continue
33 
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>Multi user chat without nickname</title>
 6 </head>
 7 <body>
 8 <div id="chat_room">
 9     <p>Enter your nickname to enter the multiplayer chat room:<input type="text" id="client_name"></input>
10         <button id='login' onclick="login()">Sign in</button>
11     </p>
12     <p id='chat_msg' hidden="hidden">Please enter chat content:<input type="text" id="msg">
13         <button id="send" onclick="send()">send out</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     //Send the local nickname to the server
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    //Listen for messages from the server (json data)
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     //Chat message sending (json data)
47     function send() {
48         var msg = document.getElementById('msg').value;
49         var data = {
50             name: name,
51             msg: msg
52         };
53         var data_json = JSON.stringify(data);
54         ws.send(data_json);
55     }
56 </script>
57 </html>

MUC_nick.html

(3) Private chat instant messaging based on websocket + Flash

flask_websocket(Private_chat).py

1 '''
 2 be based on websocket+flask Private chat instant messaging
 3 Design dictionary client_dict = {}To store{Client Name: the connection between the client and the server},The name of the client is obtained through dynamic routing parameters,
 4 Information sent by the server through the client (via json The name of the target client in the serialized Dictionary), obtain the connection of the target client in the storage dictionary and forward it directly
 5 '''
 6 from flask import Flask, render_template, request
 7 from geventwebsocket.handler import WebSocketHandler  # Provide WS (websocket) protocol processing
 8 from geventwebsocket.server import WSGIServer  # websocket service bearer
 9 from geventwebsocket.websocket import WebSocket  # websocket syntax tips
10 import json
11 
12 app = Flask(__name__)
13 
14 client_dict = {}
15 
16 
17 @app.route('/websocket/<client_name>')  # To obtain nicknames through dynamic routing parameters, you must define a formal parameter with the same name in the view function
18 def websocket(client_name):
19     client_socket = request.environ.get('wsgi.websocket')  # type:WebSocket
20     client_dict[client_name] = client_socket
21     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                 continue
30 
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>Single person chat room</title>
 6 
 7 </head>
 8 <body>
 9 <div id="chat_room">
10     <p>Enter the nickname to enter the single person chat room:<input type="text" id="client_name"></input>
11         <button id='login' onclick="login()">Sign in</button>
12     </p>
13     <p hidden id="client_recv">To:<input type="text" id="to_client"></p>
14     <p id='chat_msg' hidden="hidden">Please enter chat content:<input type="text" id="msg">
15 
16         <button id="send" onclick="send()">send out</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 instantiation
34         ws = new WebSocket('ws://192.168.16.14:8888/websocket/' + name);
35 
36         //Listen for messages from the server (json data)
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     //Chat message sending (json data)
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_client
58         };
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

Actual project background code:

#! /usr/bin/python2
#! -*- coding:utf-8  -*-

from flask import Flask,request
from gevent import monkey
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
import time
import json
import sys
import traceback
import logging
from InteractiveWithDatabase.interactive_with_database import Get_first_record_from_database
from pub.const_redis import SYSTEM_KEY_NAME
from MEO_DB import redisLifecycle
monkey.patch_all()  #Support asynchronous requests

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 ''


# There must be receive blocking before the server is shut down, otherwise both the server and the client will crash due to dead circulation
# The principle of websocket: the client sends a message request, and the server replies to the data [if the client does not send a message, the loop will not block, that is, an endless loop]

if __name__ == '__main__':
    http_serv=WSGIServer(("0.0.0.0",int(sys.argv[1])),app,handler_class=WebSocketHandler)
    http_serv.serve_forever()

Front end processing of actual project:

{% block scripts %}
{{super()}}
<script type="text/javascript" src="{{url_for('static',filename = 'js/system.js')}}"></script>
<script>
    //Continuous monitoring function of access system connection status
    var web_socket_msg = {{extraData|tojson}}
    console.log(web_socket_msg)
    var vnfms = {{resData.vnfms|tojson}}
    function con_svr(vnfm_id){
         // The protocol is ws, which works with http, wws and 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 + 'Connection successful')
          ws.send(vnfm_id)
        }
        ws.onmessage = function (e) {
          console.log(vnfm_id + 'Server response received', 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 %}

Keywords: Python http websocket python-web

Added by xluminex on Thu, 10 Feb 2022 22:37:49 +0200