HTTP流-广播,正在等待n个客户端

时间:2018-10-31 18:04:03

标签: node.js http client streaming wait

我想通过nodejs将文件流传输到多个客户端。 假设我希望有5个客户端连接到服务器,然后服务器“广播”视频内容。

到目前为止,我的代码还可以流式传输文件:

const express = require("express");
const fs = require("fs");


const app = express();
app.listen(8081);

app.get('/video', function (req, res) {


  const path = './video.webm';
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;

  if (range) {

    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
    const chunksize = (end - start) + 1;
    const file = fs.createReadStream(path, {start, end});

    const head = {
      'Content-Range': "bytes ${start}-${end}/${fileSize}",
      'Accept-Ranges': 'bytes',
      'Content-Length': chunksize,
      'Content-Type': 'video/webm'
    };


    res.writeHead(206, head);
    file.pipe(res);

  } else {

    const head = {
      'Content-Length': fileSize,
      'Content-Type': 'video/webm'
    };

    res.writeHead(200, head);
    fs.createReadStream(path).pipe(res)

  }
});

效果很好,但是缺少“等待5个客户端”代码。

我不知道该如何存档。 主要问题是:我如何告诉客户,将来会有内容,而他不关闭连接?

那是我尝试过的(不是我想要的方式,只有最后一个客户才能获得内容):

var counter = 0;

app.get('/video', function (req, res) {
  
  counter++;

  const path = './video.webm';
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;

  const head = {
    'Content-Length': fileSize,
    'Content-Type': 'video/webm'
  };

  res.writeHead(200, head);
  
  
  const wait = setInterval(function () {
    res.write("");
  }, 1000);
  
  if(counter === 2){
    
    clearInterval(wait);
    fs.createReadStream(path).pipe(res);
    
  }


});

“ setInterval”是必需品吗?

感谢任何想法和建议

编辑:那就是我想要的,但是它不是真正的“实时”时间。 Stream适用于所有客户端,但是有一点延迟。有没有办法同步流?

var counter = 0;
var requests = [];

app.get('/video', function (req, res) {
  
  counter++;

  const path = './video.webm';
  const stat = fs.statSync(path);
  const fileSize = stat.size;
  const range = req.headers.range;

  const head = {
    'Content-Length': fileSize,
    'Content-Type': 'video/webm'
  };

  res.writeHead(200, head);
  requests.push(res);
  
  
  const wait = setInterval(function () {
    res.write("");
  }, 1000);
  
  if(counter === 2){
    
    clearInterval(wait);
    const stream = fs.createReadStream(path);
    
    stream.on("error", function(err){
      console.log(">>", err);
    });
    
    requests.forEach(function(client){
      stream.pipe(client);
    });
    
    
    
  }

});

0 个答案:

没有答案