Reputation: 730
i am having problem with the socket.emit using socket.io. i have an object of connected clients, when i emit a message to a specific client using socket.emit, it emits two times! any solution.
here is the code.
var clients ={};
io.sockets.on('connection',function(socket){
socket.on('verifyId',function(data){
clients[data.user_id]=[];
clients[data.user_id].push(socket);
});
socket.on('saveConverse',function(data){
user1=clients[data.to];
if(clients[data.to])
user1[0].emit('newMessage',{msg:'hi, here is a new message!'});
//here it is emitted two times.
});
});
Upvotes: 0
Views: 861
Reputation: 1351
Try replacing
user1[0].emit('newMessage',{msg:'hi, here is a new message!'});
with this:
io.sockets.socket(socketid).emit('newMessage',{msg:'hi, here is a new message!'});
Because this is the proper way to emit to a specific client. Aslo,
you can save socket IDs instead of the whole socket object in clients
array by socket.id
.
Upvotes: 0