I am using current versions of all things node.js, express.js, socket.io etc ... I am trying to connect to a server who's sole purpose in life is just spew text and in turn send it to web client connected via socket.io. The text is nothing more character strings with standard line endings and the max data rate is something on the order of 1024bytes/sec. My code, the core bits, is something like this
var express = require('express')
, app = express()
, routes = require('./routes')
, user = require('./routes/user')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, path = require('path')
, dataSourcePort = 5000
, host = "10.0.1.32"
, dataStream = require('net').createConnection(dataSourcePort, host);
dataStream.setEncoding('utf8');
io.sockets.on('connection', function (socket) {
dataStream.on('data',function(data){
socket.emit("stuff",data);
});
});
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
This works all fine and dandy but, every once in a while it just hangs, as in the data stops going out to the clients. I assume a buffer gets stuffed somewhere along the line but, not sure. Is there a better way to do this and avoid the stuffing part?
The main issue I see is that you never unbind your data handler, so as people connect and disconnect, you will accumulate data listeners and memory usage, and waste resources trying to send data to disconnected sockets.
io.sockets.on('connection', function (socket) {
function ondata(data){
socket.emit("stuff",data);
}
function ondisconnect(){
dataStream.off('data', ondata);
socket.off('disconnect', ondisconnect);
}
dataStream.on('data', ondata);
socket.on('disconnect', ondisconnect);
});