NodeJS |如何将图像从套接字服务器发送到其他服务器

问题描述 投票:0回答:1

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

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

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

我想找到一种方法从Socket服务器发送到我的主服务器,流式图像和我的主服务器每次都要作为新客户端进行监听。

谢谢

javascript node.js sockets tcp
1个回答
0
投票

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

有几点需要考虑:

  • 您需要检测服务器上的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的示例

UPDATE

通过以下片段,由于实现了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
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.