如何在javascript中检测与MJPEG流的断开连接 [英] How do I detect a disconnect from an MJPEG stream in javascript

查看:32
本文介绍了如何在javascript中检测与MJPEG流的断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网页上显示来自 IP 摄像机的 MJPEG 流.流使用图像元素显示,该元素由 jQuery 设置:

I am showing an MJPEG stream from an IP camera on a web page. The stream is shown using an image element, which is set by jQuery:

view = $('<img>');

view.load(function() {
     console.log('loaded');
});
view.error(function() {
     console.log('error');
});

view.attr('src', 'http://camera_ip/videostream.mjpeg');

当它们各自的情况发生时,这两个事件都会整齐地触发.直到我断开相机.图像冻结(当然).我想检测这种断开连接,向用户显示错误消息.我想到了一个解决方案,将与图像相隔几秒钟的帧复制到画布上,然后比较内容.

Both events fire neatly when their respective situation occurs. Until I disconnect the camera. The image freezes (of course). I want to detect this disconnection, to show the user an error message. I thought up a solution, which was copying frames several seconds apart from the image to a canvas, and comparing the contents.

有更简单的选择吗?

推荐答案

我能想到的在前端执行此操作的唯一方法是在您设置图像的 src 属性时创建一个 AJAX 请求.当 mjpeg 流结束时,AJAX 请求应该调用完成"回调.

The only way I can think of doing this on the front end is creating an AJAX request exactly when you set the src attribute of the image. The AJAX request should call the "complete" callback when the mjpeg stream ends.

如果您对 node.js 和/或 websockets 感到满意,您也可以设置一个 mjpeg 代理后端,它提供 mjpeg 流并在流结束时通过 websocket 向该客户端发出关闭"事件.所以它看起来像这样(请记住,我仍然没有弄清楚 bufferToJPEG 将如何从流中解析出单个 jpeg 帧):

If you are comfortable with node.js and/or websockets, you could alternatively set up an mjpeg proxy back end that serves up the mjpeg stream and emits a 'close' event to that client over a websocket when the stream ends. So it would look something like this (keep in mind, I still haven't figured out exactly how bufferToJPEG would parse out the single jpeg frame from the stream):

http.get('http://camera_ip/videostream.mjpeg', function(response) {
    var buffer = "";

    response.on('data', function(chunk) {
        buffer += chunk;
        clientSocket.emit('imageFrame', bufferToJPEG(buffer));
    });
    response.on('end', function() {
        clientSocket.emit('imageEnd');
    });
});

这个问题(我现在正试图在我自己的项目中处理)是你必须要么将 websocket 与每个图像请求相关联,要么在 mjpeg 流进来时发出原始 jpeg通过 websockets(您可以在前端使用数据 uri 渲染这些图像).

The problem with this (which I am trying to deal with in my own project right now) is that you then have to either associate a websocket with each image request, or emit the raw jpegs from the mjpeg stream as they come in over websockets (you can render those images with data uris on the front end).

希望能帮到你——抱歉让你等了这么久才得到回复.

Hope that helped a little -- sorry you had to wait so long for a response.

https://github.com/wilhelmbot/Paparazzo.js 看起来像一个以我上面描述的方式代理该图像的好方法.

edit: https://github.com/wilhelmbot/Paparazzo.js looks like a good way of proxying that image in the way that I described above.

这篇关于如何在javascript中检测与MJPEG流的断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆