Categories
Node.js Basics

Node.js Basics — Socket.io Namespace and Rooms

Spread the love

Node.js is a popular runtime platform to create programs that run on it.

It lets us run JavaScript outside the browser.

In this article, we’ll look at how to start using Node.js to create programs.

Namespace and Express Middleware

We can use Socket.io namespaces with Express middleware.

For example, we can write:

index.js

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const options = { /* ... */ };
const io = require('socket.io')(server, options);
const session = require('express-session');
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);

io.use(wrap(session({ secret: 'cats' })));
io.on('connection', socket => {
  console.log('connect')
});

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

adminNamespace.use((socket, next) => {
  console.log(socket);
  next();
});

adminNamespace.on('connection', socket => {
  socket.on('delete user', (data) => {
    console.log(data);
  });
});

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
});

server.listen(3000);

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Minimal working example</title>
</head>

<body>
  <ul id="events"></ul>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io('/admin');
    socket.emit('delete user', 'foo')
  </script>
</body>

</html>

In index.js , we added the express-session middleware.

We combine the middleware with Socket.io with the wrap function.

The function returns a function that returns the middleware called by the middleware function with the socket.request and next function together as one.

Then we can call that function with io.use with the express-session options.

Rooms in Namespaces

We can add rooms to namespaces by calling various methods.

To join a room, we can call the socket.join method:

index.js

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const options = { /* ... */ };
const io = require('socket.io')(server, options);
io.on('connection', function (socket) {
  socket.join("room");
  io.sockets.in("room").emit('connectToRoom', "You are in room");
})

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
});

server.listen(3000);

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Minimal working example</title>
</head>

<body>
  <ul id="events"></ul>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();
    socket.on('connectToRoom', function (data) {
      document.write(data);
    });
  </script>
</body>

</html>

In index.js , we listen to the connection event.

In the callback, we call socket.join with the room name.

Then we call io.sockets.in method to emit an event in the room.

The emit method has event name the first argument and the 2nd argument is the data we want to send.

In index.html , we listen to the connectToRoom event that we emitted and get the data from the callback parameter.

We can listen to the disconnect event to watch for room disconnections.

For example, we can write:

index.js

const express = require('express');
const app = express();
const server = require('http').createServer(app);
const options = { /* ... */ };
const io = require('socket.io')(server, options);
io.on('connection', function (socket) {
  socket.join("room");
  io.sockets.in("room").emit('connectToRoom', "You are in room");
  socket.on('disconnecting', () => {
    const rooms = Object.keys(socket.rooms);
    console.log(rooms)
  });

  socket.on('disconnect', () => {
    console.log('disconnect')
  });
})

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
});

server.listen(3000);

We listen to the disconnecting and disconnect events to listen for room disconnections.

socket.rooms has all the room data.

The keys of it have the names of the rooms.

Conclusion

We can listen for room connections and disconnections and emit events to rooms from the server to the client with Socket.io.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *