komali_2 komali_2 - 5 months ago 12
Node.js Question

Should I put server-side listeners on io or socket for socket.io?

If I have my

express.js
server set up as such:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 8080;

server.listen(8080);


And elsewhere I have a
io.on('connnect', function(socket){...});
, should I be putting emit/event listeners on that socket within the
io.connect(...)
callback, or on the io object?

My basic program flow is as follows:


  1. Client socket emits
    get_new_number
    .

  2. Server receives
    get_new_number
    from unique socket.

  3. Based on that unique socket ID, it
    emits
    new_number

  4. The client listens for
    new_number
    and logs the data within to the console when triggered.



On the server-side, for part 2, I believe that must be a within the
io.on('connect'...)
function, so I can access
socket.id
for use later :

io.on('connect', function(socket){
socket.on('get_new_number', function(){
console.log('server got request for new number.');
globalVarId = socket.id;
});
});


But from there, where should I emit a new number to that unique socket? Say I save the
socket.id
and then emit to only it, how can I do that? The below isn't working:

io.on('connect', function(socket){
//get_new_number stuff
socket.to(globalVarId).emit('new_number', {number: someNumber});
});


Should I instead later do a
io.to(globalVarId).emit...
?

EDIT: For that matter, is there a way to put event listeners on the
io
object, such like

io.on('someEvent', function(socket){
console.log('this socket did a thing, ', socket.id);
});

Answer

You can assume that socket within the callback function represents a unique client/connection.

So when you want to communicate with that client, you can use socket.emit():

io.on('connect', function(socket) {
  socket.on('get_new_number', function() {
    console.log('server got request for new number.');
    //get_new_number stuff
    socket.emit('new_number', { number: someNumber });
  });
});

.to(...).emit(...) is used for something else entirely (sending a message to a particular room).

Comments