I want to have a real-time connection between many group of users and i am new to server side scripting.........I want to send certain messages(data) to certain users, now my question is how to do it either to have a same socket for all users or different sockets connection for different users or for different task ..?
Currently I am just using a single socket and serving users this way..This is not the actual app its just a prototype of what I will be doing:
var io = require('socket.io').listen(server);
server.listen(http_port);
var allUsers=[];
var num=1;
io.sockets.on('connection', function (socket) {
var user = 'user#'+num++;
allUsers[user] = socket;
socket.on('message',function(data){
if(data.to)
allUsers[data.to].emit("message",{msg:data.msg,by:data.by});
});
});
Client side:
socket.emit('message',{to:'user#1',from:'talha',msg:'hello'});
Maybe, I am on a wrong approach, becuase later on I will be quering to database sending those results to specific clients, how do i manage that.
Please provide some code details along with your anwers .. Thanks in advance.
No, you only have one listening socket. On each connection (as it can be seen from io.sockets.on('connection', function(socket){..) , your function(socket){....} is called and the socket in that function is identical to each connection/user. The function callbacks on "connection" event are sepearate and one for each user.
EDIT: For user seperating users you can do the following:
var users = [];
io.sockets.on("connection", function(socket){
socket.on("message", function(data){
// Handle if it is a valid user, make some authentication and have a username..
users[username] = socket;
// on another message, if you want to send message
users["myuser"].send(...)
}
});