Refresh technology demonstration based server push pictures

最近在做一个类似直播平台的网络应用,想要使前端能不断的从服务器获取视频流。
首先我们要选择一种服务器与浏览器连接方式。目前主要有短链接与全连接两种。
其中短连接又分为传统轮询与长轮询。
轮询(属于短链接):客户端定时向服务器发送Ajax请求,服务器接到请求后马上返回响应信息并关闭连接。 

Pros: the back-end programming easier.
Cons: There are more than half of the request is useless and a waste of bandwidth and server resources.
Example: suitable for small applications.
Long polling (short connecting belongs, belongs to technical comet): Ajax client sends a request to the server, the server hold live connection upon request, does not return until a new message response information and then close the connection, the client information processing complete response send a new request to the server. Compared with the short polling is actually increasing the time-out only. Diagram below
Here Insert Picture Description
web client code is as follows:

//向后台长轮询消息
    function longPolling(){
        $.ajax({
            async : true,//异步
            url : 'longPollingAction!getMessages.action', 
            type : 'post',
            dataType : 'json',
            data :{},
            timeout : 30000,//超时时间设定30秒
            error : function(xhr, textStatus, thrownError) {
                longPolling();//发生异常错误后再次发起请求
            },
            success : function(response) {
                message = response.data.message;
                if(message!="timeout"){
                    broadcast();//收到消息后发布消息
                }
                longPolling();
            }
        });
    }

Advantages: not frequently request message without a case, small consumption of resources.
Cons: server hold the connection will consume resources, to ensure that no data is returned order, difficult to manage and maintain.
Examples: WebQQ, Hi web version, Facebook IM.
Long connection: http1.1 long connection protocols are used by default, that is, the browser and the server is always connected, even if there is no data to be transferred. It is mainly used in situations frequently send data, so you can reduce connection costs.
Advantages: Instant message arrival, do not send useless request; also is relatively easy to manage.
Cons: server maintains a persistent connection will increase overhead.
Example: Gmail chat
long link two major categories, one is the way simplex communication server push message to the client, and both websocket communication may transmit data to each other.
Technical simplex communication for the byte stream are based on the real-time push ajax byte stream, two modes based SSE (Server-Event Events). In javascript advanced programming have a more detailed explanation. If the server push is needed to refresh the picture directly specified image src URL for the server push. The image refresh project belongs to simplex communication. Refresh Image primarily to pay attention to the server to specify the packet header and http protocols mineType Content-Type field. See graphic http protocol recommended this book to understand the details of the agreement.
Core server code is as follows:

     def gen(camera, start=False):
"""Video streaming generator function."""
        while start:
            frame = camera.get_frame()
            #字符串前面加b表示 后面字符串是bytes 类型。
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

    @app.route('/cv_camera')
    def cv_camera_feed():
        print("**begin**")
    	camera = Camera_cv()
    #通常一个HTTP响应只能包含一个数据块。但MIME有一种机制可用一个报文(或HTTP响应)表示将多个数据块,
    # 这种机制就是成为“multipart/mixed”的标准MIME类型。
    #这其实是一种基于服务器推送的在浏览器异步刷新的方法
    #“replace”表示每一个新数据块都会代替前一个数据块。也就是说,新数据不是附加到旧数据之后,而是替代它。
    	return Response(
        	gen(camera, True), mimetype='multipart/x-mixed-replace; boundary=frame')

Wherein camera.get_frame () function is the last one.

yield cv2.imencode('.jpg', frame)[1].tobytes()
    """简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,
    Python 解释器会将其视为一个 generator,调用 frames()不会执行frames()函数,而是返回一个 iterable 对象!
    在 for 循环执行时,每次循环都会执行 frames() 函数内部的代码,执行到 yield 语句时,fab 函数就返回一个迭代值"""

Flash Socket: embedded within a page, using the JavaScript program Flash Socket class Socket Socket server interface provided by the calling program interface to communicate this Flash, JavaScript after receiving the message transmitted from the control server the displayed page.
Pros: true instant communication, rather than a pseudo-real-time.
Cons: The client must install the Flash plug-in; non-HTTP protocol, can not automatically pass through the firewall.
Example: network interactive games.

Reference Linking
simple implementation of HTTP-based long-polling
https://www.e-learn.cn/content/jquery/1155365
https://www.cnblogs.com/leaven/p/3514650.html

Guess you like

Origin blog.csdn.net/qq_25349323/article/details/90261549