NodeJS |如何将图像从套接字服务器发送到另一台服务器

时间:2019-04-05 10:21:48

标签: javascript node.js sockets tcp

我正在研究一个新项目,我想问你一个我面临的问题。

我有一个运行socket.io模块的Web服务器。该服务器监听其端口(3012),然后使用套接字将图像流式传输到客户端。

我的主服务器具有不同的端口(4049)。该服务器的前端部分包括一个空白容器。

我想找到一种方法,从套接字服务器向我的主服务器发送流式图像,然后让我的主服务器每次以新客户端的身份进行侦听。

谢谢

1 个答案:

答案 0 :(得分:0)

您需要做的是,每次在客户端上的映像.on('data')上触发Readable stream事件时,都将块发送到套接字服务器,然后在收到块时将它们写入到Writeable Stream在websocket服务器端。

有几点需要注意:

  • 您将需要检测服务器上的EOF(检查特定的文件类型EOF字节),或从客户端发出某种报头。例子。
const EOF = Buffer.alloc(6);

// Client Side

client.sendBytes(EOF); // on end

// Server
if(chunk.slice(-6).compare(EOF) === 0)
  console.log('File EOF close write stream');
  • 如果同时读取多个图像,则需要为每个块添加一个标识符,以便在服务器端正确写入。标识符的长度应始终相同,因此您可以在服务器端正确切片缓冲区。
const imageOne = fs.createReadStream('./image-1.jpg');
const imageTwo = fs.createReadStream('./image-2.jpg');

// This will be mixed, and you'll end up with a broken image
imageOne.on('data', chunk => client.sendBytes(chunk)); // add identifier
imageTwo.on('data', chunk => client.sendBytes(chunk)); // add identifier

以下是使用websocket软件包的示例。

服务器

/* rest of implementation */
wsServer.on('request', function(request) {
  const connection = request.accept(null, request.origin);

  const JPEG_EOF = Buffer.from([0xFF, 0xD9]);
  let stream = null;

  connection.on('message', function(message) {
    if (message.type === 'binary') {

      if(!stream) {
        stream = fs.createWriteStream(generateImageName())
         // this could be any Writable Stream
         // not necessarily a file stream.
         // It can be an HTTP request for example.
      }

      // Check if it's the end
      if(JPEG_EOF.compare(message.binaryData) === 0) {
        console.log('done');
        stream.end(message.binaryData);
        stream = null;
        return;
      }

      // You will need to implement a back pressure mechanism
      stream.write(message.binaryData)    
    }
  });
});

客户

/** ... **/
client.on('connect', function(connection) {

  fs.createReadStream('./some-image.jpg')
    .on('data', chunk => {
        connection.sendBytes(chunk);
    });

});
/** ... **/

上面的示例仅处理jpeg张图片,因为它直接检查jpeg的后2个字节,因此您可以为其他文件类型实现逻辑。

在该示例中,我假设每个连接一次只能流送1张图像,否则它将变得混乱。

现在,您需要为.write实现背压机制,这意味着您必须检查返回值并等待drain事件。 稍后,当我有更多时间来正确处理背压时,我将使用自定义Readable stream提交示例

更新

使用以下代码段,由于实现了Readable流,因此我们可以使用.pipe来处理背压。

const { Readable } = require('stream');

class ImageStream extends Readable {

  constructor() {
    super();

    this.chunks = [];
    this.EOF = Buffer.from([0xFF, 0xD9]);
  }

  add(chunk) {
    this.chunks.push(chunk);    

    if(this.isPaused()) {
      this.resume();

      // Need to call _read if instead of this.push('') you return without calling .push
      // this._read(); 
    }
  }

  _read() {

    const chunk = this.chunks.shift();

    if(!chunk) { // nothing to push, pause the stream until more data is added
      this.pause(); 
      return this.push(''); // check: https://nodejs.org/api/stream.html#stream_readable_push
      // If you return without pushing
      // you need to call _read again after resume
    }

    this.push(chunk);

    // If the last 2 bytes are not sent in the same chunk
    // This won't work, you can implement some logic if that can happen
    // It's a really edge case.
    const last = chunk.slice(-2);
    if(this.EOF.compare(last) == 0)
      this.push(null); // Image done, end the stream.

  }
}

/* ... */
wsServer.on('request', function(request) {
  const connection = request.accept(null, request.origin);

  let stream = null;

  connection.on('message', function(message) {
    if (message.type === 'binary') {

      if(!stream) {
        stream = new ImageStream();
        stream.pipe(fs.createWriteStream(generateImageName()));
        // stream.pipe(request(/* ... */));
        stream.on('end', () => {
          stream = null; // done
        });
      }

      stream.add(message.binaryData);
    }
  });

  connection.on('close', function(connection) {
    // close user connection
  });
});