Node.js Socket.io seperate connection events for each page

417 views Asked by At

I've taken the following code from Socket.io documentations page.

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

app.use(express.static(__dirname + '/public'));

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

I would like to have a separate 'connection' event depending on the page that made the request. E.g.

Clients connected from the 'index' page trigger this event.

io.on('connection', function (socket) {
  console.log('connected from the index page');
});

and clients connected from the 'player scores' page trigger this event

io.on('connection', function (socket) {
  console.log('connected from the index page');
});

I've considered using namespaces. Is there a way that I could do this without out the client having to specify that it has connected from a particular page?

Regards,

1

There are 1 answers

0
Sander Thomassen On

You could use the handshake data in the socket object to get the URL and then program the different pieces of logic in an if-statement. Something along these lines:

io.on('connection', function (socket) {
  if(socket.handshake.url == "index url you expect"){
    console.log('connected from the index page');
  } else if(socket.handshake.url == "player scores url you expect"){
    console.log('connected from the player scores page');
  }
});