So we have the following node.js code -
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
response.end(");
}).listen(8125);
Let's say I want to broadcast a message to all the connected users,
write method of response in the createServer function doesn't do that.
So how can I broadcast message to all the connected users/clients?
There is a way doing it with pure Node.js? because I'm just learning it now, and I prefer using pure node.js for now..
These are HTTP requests, therefore it isn't possible. HTTP requests start on first connection and end when all the data has been sent.
In your case, the data is
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
And then connection is ended
response.end(");
If you're looking for something to keep live connections with, take a look at these:
socket.io - a realtime transport library that supports all platforms, and falls back for older software.
WebSocket-Node - a client and server websocket implementation.
Faye - publish-subscribe messaging system that uses the Bayeux protocol.
I have only used socket.io and this is how broadcasting is done.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
});