Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io send packet to sender only

I have yet to figure out how to directly respond to only the sender using socket.io

I have learned that io.sockets.emit sends to all clients but I wont to send information back to the sender.

code:

socket.on('login', function (data) {     db.users.find({username: cc.lowerCase(data.username)}, function(err, users) {       if (users.length > 0) {         users.forEach( function(user) {           console.log(user.length);           if (user.password == data.password) {             io.sockets.emit('login', { username: user.username });           } else {             io.sockets.emit('error', { message: "Wrong username or password!" });           }         });       } else {         io.sockets.emit('error', { message: "Wrong username or password!" });       }     }); }); 
like image 271
Zander17 Avatar asked Jun 07 '14 18:06

Zander17


1 Answers

When your server listens, you usually get a socket at the "connection" event :

require('socket.io').on('connect', function(socket){ 

A socket connects 2 points : the client and the server. When you emit on this socket, you emit to this specific client.

Example :

var io = require('socket.io'); io.on('connect', function(socket){     socket.on('A', function(something){         // we just received a message         // let's respond to *that* client :         socket.emit('B', somethingElse);     }); }); 

Be careful that those are two different calls :

  • socket.emit : emit to just one socket
  • io.sockets.emit : emit to all sockets
like image 51
Denys Séguret Avatar answered Oct 01 '22 12:10

Denys Séguret