I’m messing around with Node JS and socket.io and I’m a bit lost. In the following code I’m saving references to the socket upon creation then transmiting messages captured from the console. all works well, but I feel like this is not the right approach.
Your thoughts?
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(80);
function handler(req, res) {
fs.readFile('C:/node/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var Sender = {
sockets:[],
sendMsg:function (msg) {
for (var i = 0; i < Sender.sockets.length; i++) {
Sender.sockets[i].emit('news', msg);
}
}
};
process.openStdin().addListener("data", function (text) {
Sender.sendMsg(text.toString());
});
io.sockets.on('connection', function (socket) {
//Saving reference
Sender.sockets.push(socket);
});
Indeed, you can remove your
Senderand all references to it.This will emit the message to all connected clients.
There are a few examples on http://socket.io/, I suggest you check them out.