I am using Node js and socket.io for implementing basic chat application. Every client that writes any message is broadcast-ed to all clients that are connected to server (Its a cross browser application). Now i want only one client that gets first access to server can forward messages to all while other subscribed users can ONLY receive messages (can not send data to any one). My question is how should i identify the client on server when ever it gives request for sending data to all?
This is server side implentation:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res)
{
res.sendfile(__dirname + '/index.html');
});
io.set('log level', 1);
io.sockets.on('connection', function(socket)
{
socket.emit('news', "Hello, welcome to our conversation!<br />");
socket.on('receive', function(data)
{
//log it to console
console.log(data.data);
// announce to all clients that someone sent you data.
socket.broadcast.emit('news', "Client says: " + data.data + "<br />");
});
});
You can identify each socket using it's unique id: socket.id Perhaps you can do something like this to stop everyone except the first socket from broadcasting.
var firstClient;
io.sockets.on('connection', function(socket)
{
if(!firstClient){
firstClient = socket.id;
}
socket.emit('news', "Hello, welcome to our conversation!<br />");
socket.on('receive', function(data)
{
if(socket.id!==firstClient){
return; // not the first client, so not allowed to broadcast.
}
//log it to console
console.log(data.data);
// announce to all clients that someone sent you data.
socket.broadcast.emit('news', "Client says: " + data.data + "<br />");
});
});