tonyf
tonyf

Reputation: 35557

How to assign a unique identifier to a Websocket

Using socket.ioin a Node/Express environment, is it possible to uniquely assign, say someone's login id, when a socket connection is made?

Updated

Within my app.js (express) file, I have the following code to access the login, from the request headers:

const express = require('express');
const app = express();

app.use(function(req, res, next){        
  let login = req.header('login');
  next();
});

I need a means of being able to broadcast messages using this unique identifier (login) via socket.io

Upvotes: 0

Views: 1817

Answers (1)

jfriend00
jfriend00

Reputation: 707456

OK, I'll assume that you have the ability to figure out which user it is from the login cookie. Since you don't show us how you set up the cookie, you will have to write your own code to do that.

When a socket.io connection event occurs, you can get to the cookies from the initial socket.io connection request in socket.request.headers.cookie. Let's assume you have a function named getUserFromCookie() that you pass a login cookie to and it returns the userID and we'll assume your login cookie is named "login". Then, you could write code like this:

io.on('connection', socket => {
    let userId = getUserFromCookie(socket.request.headers.cookie);
    // join user to a room with the name of their userId
    socket.join(userId);
});

Then, elsewhere in your server code where you want to send a message to a particular userId, you can do it by just doing this:

io.to(userId).emit("someMsg", someData);

Upvotes: 2

Related Questions