Handling users with Simple Way To Emit Messages By User Id


On the server:

var express = require('express');
var socketio = require('');

var app = express();
var server = http.createServer(app);
var io = socketio(server);

io.on('connect', function (socket) {
  socket.on('userConnected', socket.join);
  socket.on('userDisconnected', socket.leave);

function message (userId, event, data) {, data);

On the client:

var socket = io('http://localhost:9000');  // Server endpoint

socket.on('connect', connectUser);

socket.on('message', function (data) {

function connectUser () {  // Called whenever a user signs in
  var userId = ...  // Retrieve userId
  if (!userId) return;
  socket.emit('userConnected', userId);

function disconnectUser () {  // Called whenever a user signs out
  var userId = ...  // Retrieve userId
  if (!userId) return;
  socket.emit('userDisconnected', userId);

This method allows sending messages to specific users by unique id without holding a reference to all sockets on the server.