user687554
user687554

Reputation: 11151

Socket.io on specific endpoint

I'm learning how to use Socket.io. My website is built on Node.js and express. In this site, I have a number of views. However, I only want to use sockets on one specific view /dashboard/stream. In other words, I only want to turn on sockets if something visits /dashboard/stream. All of the documentation I read implies that I need to configure sockets at the app level in express. In other words, it looks like it's always on. So, if someone uses my website, but never visits /dashboard/stream, sockets would still be running on the server.

Am I missing something? Is there a way to say "if someone visits /dashboard/stream activate sockets for the user?

Thank you for helping me gain clarity on this.

Upvotes: 4

Views: 7044

Answers (2)

Flecibel
Flecibel

Reputation: 186

The correct way to implement listening on an endpoint is namespaces.

const nsp= io.of('/admin');

nsp.use((socket, next) => {
  // ensure the user has sufficient rights
  next();
});

nsp.on('connection', socket => {
  socket.on('delete user', () => {
    // ...
  });
});

https://socket.io/docs/v3/namespaces/#Custom-namespaces

Upvotes: 3

Andrii Dobroshynski
Andrii Dobroshynski

Reputation: 311

Socket.io requires access to the underlying HTTP server object that backs express.

So in simplest form, as I'm sure you probably checked out on docs you attach a socket.io Server to Express using something like this

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

So its designed so that you're effectively binding it to the http server, and then proceed with doing io.on, io.emit and all that stuff. Now as far as where you put the code for actually binding socket.io to express, I'm guessing you could place it anywhere you want, if you don't want with all initial setup, and then simply define your socket.on at the specific route in route handler.

Hope this helps a bit!

Upvotes: 2

Related Questions