socket io path code example

Example 1: socket io connect to namespace

var io  = require('socket.io')(http, { path: '/myapp/socket.io'});

io
.of('/my-namespace')
.on('connection', function(socket){
    console.log('a user connected with id %s', socket.id);

    socket.on('my-message', function (data) {
        io.of('my-namespace').emit('my-message', data);
        // or socket.emit(...)
        console.log('broadcasting my-message', data);
    });
});

Example 2: socket io middleware

const express = require('express');
const socketio = require('socket.io');

// Setup server and socket
const port = 3000;
const app = express();
const server = app.listen(port, console.log(`Listening on port ${port}...`));
const io = socketio(server);

// Calls the middleware on every new connection
io.use((socket, next) => {
  if (/* should connect socket */) {
    next();
  } else {
    next(new Error('Connection failed.'));
  }
});

io.on('connection', (socket) => {
  // Calls the middleware on every event
  socket.use((packet, next) => {
    const event = packet[0];
    const data = packet.slice(1);
    
    if (/* should run event */) {
      next();
    } else {
      next(new Error('Failed to emit the event.'));
    }
  });

  // Example event
  socket.on('msg', (data) => {
    socket.broadcast.emit('msg', data.msg);
  });
});