首页 > 解决方案 > 如何使用 node.js 流式传输 mjpeg

问题描述

我需要使用通过 HTTP 流式传输 mjpeg 文件的 restify 创建一个服务器脚本,问题是我首先不知道我应该为此遵循哪些步骤,例如我有几张图片,我应该将它们组合为 mjpeg首先文件然后通过 HTTP 响应发送这个 mjpeg 文件,编码为 multipart/mixed 还是什么?感谢您的回答。正如我从其他 .mjpeg 服务器所理解的那样,响应应该永远不会结束?

标签: node.jsexpressjpegrestifymjpeg

解决方案


我已经创建了这种服务器脚本,但它没有按我的意愿工作,我的意思是如果我通过单击键盘上的 F5 刷新页面,响应会使用下一个图像重新加载。可能是restify框架造成的,没有restify这个运行良好。

server.get("/app", (req, res, next) => {

    res.writeHead(200, {
        'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0',
        Pragma: 'no-cache',
        Connection: 'close',
        'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary'
    });

    setTimeout(() => {

        if(bufferIndex == bufferArray.length)
           return bufferIndex = 0
        res.write(`--myboundary\nContent-Type: image/jpg\nContent-length: ${bufferArray[bufferIndex].length}\n\n`);
        res.write(bufferArray[bufferIndex]);
        bufferIndex++

    }, 1000)
    next()

});



socketio.on('connection', (socket) => {

    console.log(socket.id)

})


server.listen(3000, function () {
    console.log('%s listening at %s', server.name, server.url);
});

推荐阅读