2017-04-02 117 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,因爲此解決方案不起作用。 –

相關問題