komali_2 komali_2 - 1 year ago 50
Node.js Question

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

If I have my

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;


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

My basic program flow is as follows:

  1. Client socket emits

  2. Server receives
    from unique socket.

  3. Based on that unique socket ID, it

  4. The client listens for
    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
function, so I can access
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
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

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

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

Answer Source

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).