I'm trying to stream data from a server to a client using websockets -- in particular, ws and websocket stream. However, the stream seems to be closing too early, and I only receive two chunks worth of data. Here is the simple example.
I have a server:
var WebSocketServer = require('ws').Server;
var websocketStream = require('websocket-stream');
var wss = new WebSocketServer({port: 8098});
var fs = require('fs');
var util = require('util');
wss.on('connection', function connect(ws) {
var stream = websocketStream(ws);
var rs = fs.createReadStream('foo.big');
rs.pipe(stream);
});
and a client that connects and streams foo.big to a local file using pipe():
var fs = require('fs');
var util = require('util');
var websocket = require('websocket-stream');
var rs = fs.createWriteStream('big.out');
rs.on('open', function () {
var ws = websocket('http://localhost:8098');
ws.on('open', function () {
ws.pipe(rs);
}).on('error', function (err) {
console.log(err);
}).on('close', function (err) {
console.log("Closing");
});
});
Any ideas why I would only be getting a few packets of data? If I remove the call in the client to pipe, and just receive the data in chunks, it seems to receive all the data.
There is a couple of things wrong with the above (as of 2017).
fs.readStream()
close
eventwebsocket-stream
open
event, as you can assume it to be openAlso, performance:
ws
is likely not suited for server to server communication. Consider alternatives, likenet
, like here, or various other lower thanws
level ways.Find a full example here on my GH.