2017-04-02 99 views
4

我正在使用node.js BinaryServer来流式传输二进制数据,并且我想在客户端调用.Stream.end()函数后从服务器发起回调事件。Node.js BinaryServer:在流结束时向客户端发送消息?

我似乎无法理解 - 当node.js服务器实际关闭流连接时,如何发送消息或某种通知?

节点JS:

server.on('connection', function(client) { 

    client.on('stream', function (stream, meta) { 

     stream.on('end', function() { 
      fileWriter.end(); 
      // <--- I want to send an event to the client here 
     }); 
    }); 

}); 

客户端JS:

client = new BinaryClient(nodeURL); 
window.Stream = client.createStream({ metaData }); 
.... 
window.Stream.end(); 
// <--- I want to recieve the callback message 
+0

上的节点JS的一面,你可以试试'client.send( “结束”)' –

+0

@ExplosionPills而我应该在客户端做什么? –

+0

收听'stream'事件,'client.on(“stream”,data =>/*对数据做一些操作* /)' –

回答

1

在服务器端,可以发送数据流给客户端.send。您可以发送各种数据类型,但在这种情况下,一个简单的字符串可能就足够了。

在客户端,您还可以收听'stream'事件以从服务器接收数据。

节点JS:

server.on('connection', function(client) { 
    client.on('stream', function (stream, meta) { 
     stream.on('end', function() { 
      fileWriter.end(); 
      client.send('finished'); 
     }); 
    });  
}); 

客户端JS:

client = new BinaryClient(nodeURL); 
client.on('stream', data => { 
    console.log(data); // do something with data 
}); 
window.Stream = client.createStream({ metaData }); 
.... 
window.Stream.end(); 
+0

我添加了你建议的代码,但是'client.on('stream',data =>'永远不会被触发 –

+0

Downvoting,因为此解决方案不起作用。 –

相关问题