0

I'm having a problem sending data to a specific client.

Serverside

var io = require('socket.io').listen(app.listen(app.get('port')));

io.sockets.on('connection', function (socket) {

    socket.on('onHabboConnection', function (data) {
      socket.id = data.id; 
      socket.join(data.id);
      io.sockets.in(data.id).emit('onHabboConnected');
    });
    
    socket.on('onHabboConnected', function (data) {
      console.log("<" + socket.id + "> " + data.username + " has joined the game.");
    });
});

Clientside

   var socket = io.connect('http://localhost:3000');
               $( document ).ready(function() {
   socket.emit('onHabboConnection', { id:'<%= user.id %>' });
  });

   socket.on('onHabboConnected', function () {
    console.log("WORKING" );
    socket.emit('onHabboConnected', { username: '<%= user.username %>'});
   });

  io.sockets.in(data.id).emit('onHabboConnected');

I've attempted all over methods but they all throw errors. This one doesn't throw an error but doesn't do anything!

king
  • 11
  • 5

1 Answers1

0

You are overwriting the unique identifier socket.id that was generated on the client side. That's why you are emitting but it's not going anywhere since that client doesn't exist:

socket.on('onHabboConnection', function (data) {
  //socket.id = data.id;  remove this
  socket.join(data.id);
  io.sockets.in(data.id).emit('onHabboConnected');
});

If you want to change socket.id , then change it on client side.

hassansin
  • 16,918
  • 3
  • 43
  • 49
  • But won't another user be able to change the userid through clientside? – king Jul 06 '15 at 19:51
  • socket id is uniquely generated session identifier for a client. Why do you need to change it? – hassansin Jul 06 '15 at 20:06
  • in that case, change it from client side. But yes another user might be able to change it. Probably you need to add some authentication like mentioned [here](http://stackoverflow.com/questions/4753957/socket-io-authentication) – hassansin Jul 06 '15 at 20:28
  • I'm using, socket.emit to send to the specified incoming client. Is that okay? – king Jul 06 '15 at 20:34