Node.js - Socket.IO support

Updated

Introduction

Socket.IO is a higher-level real-time communication framework that is often mentioned alongside WebSocket. It can use WebSocket as a transport, yet it adds its own protocol, message model, reconnection behavior, and fallback mechanisms. This extension supports the following Socket.IO libraries:

Objects

Metamodel name Description
CAST_NodeJS_WebSocket_Server Represents a WebSocket server endpoint identified by its path
CAST_NodeJS_WebSocket_Client Represents a WebSocket client entrypoint identified by its path

A NodeJS WebSocket Server object is created as soon as the server is instantiated (require('socket.io')(httpServer, opts)), even if no handler is ever registered on it and it never sends any data. A server is named {} when its path cannot be statically determined (for example when the path is passed as a runtime parameter). A server named {} is treated as a catch-all endpoint.

A NodeJS WebSocket Client object is created as soon as the client is instantiated (io(url) (imported from socket.io-client)), even if no handler is ever registered on it and it never sends any data. A client is named {} when its path cannot be statically determined (for example when the path is passed as a runtime parameter).

Link type From To Created when
callLink NodeJS WebSocket Server NodeJS Function / Method A handler is registered on the server, a namespace or a server-side socket (on('connection', ...), of('/ns').on(...), use(...), onAny(...), socket.on('event', ...))
callLink NodeJS Function / Method NodeJS WebSocket Server A function emits on the server, a namespace or a server side socket (io.emit(...), io.to(room).emit(...), socket.emit(...), socket.broadcast.emit(...))
callLink NodeJS Function / Method NodeJS WebSocket Client A function opens a client connection (io(url), io.connect(url), manager.socket('/ns')) or emits on a client socket (socket.emit(...))
callLink NodeJS WebSocket Client NodeJS Function / Method A handler is registered on a client socket socket.on('event', ...),once(...), onAny(...))

Supported API methods

Server side

API method Object created / linked Link type
require('socket.io')(httpServer, opts) / socketi (port) NodeJS WebSocket Server (main namespace /) —
new Server(httpServer, opts) / Server(httpServer) NodeJS WebSocket Server(main namespace /) —
require('socket.io').listen(port) / socketio.attac (httpServer) NodeJS WebSocket Server (main namespace /) —
io.of('/admin NodeJS WebSocket Server (namespace /admin) —
io.of(/^\/dynamic-\d+$/) / io.of((name, auth, next) => ...) NodeJS WebSocket Server (dynamic namespace {}) —
io.on('connection', fn) / nsp.on('connection', fn fn linked as callee of server (namespace) callLink
io.on(event, fn) / once / addListener / prependListener / prependOnceListener fn linked as callee of server (namespace) callLink
io.use(fn) fn (middleware) linked as callee of server (namespace) callLink
io.onAny(fn) / prependAny / onAnyOutgoing / prependAnyOutgoing fn linked as callee of server (namespace) callLink
socket.on('event', fn) / socket.once(...) on a connection socket fn linked as callee of server (see resolution rule) callLink
socket.use(fn) / socket.onAny(fn) on a connection socket fn linked as callee of server (see resolution rule) callLink
io.emit(...) / nsp.emit(...) / send / write / emitWithAck enclosing function linked as caller of server (namespace) callLink
io.to(room).emit(...) / in / except / volatile / compress / timeout / local enclosing function linked as caller of server (namespace) callLink
socket.emit(...) / socket.broadcast.emit(...) / socket.to(room).emit(...) enclosing function linked as caller of server callLink
io.on('connection', safe(fn)) / ns.bind(fn) (wrapped handler) wrapped fn linked as callee of server callLink

Client side

API method Object created / linked Link type
io(url) (imported from socket.io-client) NodeJS WebSocket Client (named after url) + enclosing function linked as caller callLink
io(url) (browser global loaded from /socket.io/socket.io.js) NodeJS WebSocket Client (named after url) + enclosing function linked as caller callLink
io() / io({ auth: ... }) NodeJS WebSocket Client (/, same origin, main namespace) + enclosing function linked as caller callLink
io.connect(url) NodeJS WebSocket Client (named after url) + enclosing function linked as caller callLink
require('socket.io-client')(url) / require('socket.io-client').connect(url) NodeJS WebSocket Client (named after url) + enclosing function linked as caller callLink
new Manager(url).socket('/admin') NodeJS WebSocket Client (scheme://host/admin) + enclosing function linked as caller callLink
this.socketIo(url) after this.socketIo = io NodeJS WebSocket Client (named after url) + enclosing function linked as caller callLink
socket.on('event', fn) / once / addListener / prependListener / prependOnceListener fn linked as callee of client callLink
socket.onAny(fn) / prependAny / onAnyOutgoing / prependAnyOutgoing fn linked as callee of client
callLink
socket.emit(...) / send / write / emitWithAck enclosing function linked as caller of client callLink
socket.timeout(ms).emit(...) / socket.volatile.emit(...) / socket.compress(false).emit(...) enclosing function linked as caller of client callLink
socket.on('event', safe(fn)) (wrapped handler) wrapped fn linked as callee of client callLink

Example

When analyzing the following files

server.ts

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { registerChatHandlers } = require('./chatHandlers');

const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer, { cors: { origin: '*' } });

app.use(express.static('public'));

function authenticate(socket, next) {
  if (socket.handshake.auth && socket.handshake.auth.token) {
    return next();
  }
  next(new Error('unauthorized'));
}

io.use(authenticate);

io.on('connection', (socket) => {
  registerChatHandlers(io, socket);
});

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

function onAdminConnection(socket) {
  socket.on('kick', (userId) => {
    io.in(userId).disconnectSockets(true);
  });
}

admin.on('connection', onAdminConnection);

function announce(message) {
  io.emit('announcement', message);
}

function notifyAdmins(event) {
  admin.emit('audit', event);
}

setInterval(() => announce('tick'), 60000);

httpServer.listen(3000, () => notifyAdmins('started'));

client.ts

const { io } = require('socket.io-client');

const adminSocket = io('http://localhost:3000/admin');

function onAudit(event) {
  console.log('audit', event);
}

adminSocket.on('audit', onAudit);

function kick(userId) {
  adminSocket.emit('kick', userId);
}

module.exports = { kick };

you will get the following result: