nodeJS视频流,当用户断开连接或移动到不同页面时,连接不会关闭

nodeJS video streaming, connection not closing when user disconnects or moved to different page

本文关键字:连接 移动 视频 用户 断开 nodeJS      更新时间:2024-03-30

我正在nodeJS中使用express构建一个视频流服务器,并使用"请求进度"模块来获取进度状态。它(视频流)运行良好。
但问题是,即使在我关闭浏览器或移动到下一页后,服务器仍在流式传输数据。我可以在控制台上看到

以下是相同的代码:

app.route('/media/*').get(function (req, res) {
  var originalUrl = "http://myactualserver.com";
  var resourceUrl = originalUrl.split('media');
  var requestURL = BASE_URL + resourceUrl[1];
  req.on('close', function () {
    console.log('Client closed the connection');
  });
  var options = {};
  progress(request(requestURL), {
    throttle: 1000,
    delay: 0,
    lengthHeader: 'content-length',
  })
    .on('progress', function (state) {
      console.log('progress', state);
    })
    .on('error', function (err) {
      console.log('err');
    })
    .on('end', function () {
      console.log('end');
    })
    .pipe(res);
});

我尝试了下面的帖子,最后添加了

req.on("close", function(){});


使用nodejs和Express 的视频流

node.js http服务器,检测客户端何时断开

Node.js服务器即使在客户端断开后仍保持流式数据

我的问题是:
1.如何调用"请求进度"的"error"或"end"函数
2.我将如何关闭流媒体
3.为什么选择console.log('Client closed the connection');被呼叫两次

问题答案:

  1. 您可能可以使用从事件发出。EventEmitter

参考本示例

https://github.com/IndigoUnited/node-request-progress/blob/master/test/test.js

或者,您可以使用关闭功能中的最后进度状态。

  1. 不确定这里的问题是什么,进程将继续,直到套接字关闭。

  2. 如果您从浏览器(默认播放器)发出请求,它会发出两个请求。