Socket.IO Driver
The Socket.IO Driver is a signaling driver that uses Socket.IO to relay signaling messages between peers through your own server. It is a good choice when you want browser and device communication over a transport you control, with support for rooms, reconnection, and the rest of the Socket.IO ecosystem.
Unlike the Memory Driver or BroadcastChannel Driver, the Socket.IO Driver works across browsers, devices, and networks because signaling messages pass through a central Socket.IO server. This makes it suitable for production deployments where peers need to discover each other outside a single page or browser context.
Usage
To use the Socket.IO Driver, import the driver from Peerix, create a Socket.IO client connection, and pass that socket to the driver instance:
import { SocketIoDriver } from 'peerix';
import { io } from 'socket.io-client';
// connect to your Socket.IO server
const socket = io('http://localhost:8080');
// create the Socket.IO driver instance
const driver = new SocketIoDriver({
// the Socket.IO client instance
socket,
// prefix for Socket.IO events
prefix: 'peerix',
});All peers that connect to the same Socket.IO server and subscribe to the same namespace can discover each other and exchange signaling messages.
Installation
You need the socket.io-client package in the browser, and a Socket.IO server implementation to forward signaling messages between clients.
npm install socket.io-client socket.ioExpected Events
The Socket.IO Driver expects the following event names. The prefix option lets you customize the event namespace used by the client and server.
- Client to server:
prefix:subscribe,prefix:unsubscribe,prefix:dispatch - Server to client:
prefix:message
This is the typical signaling flow:
sequenceDiagram
participant A as Peer A
participant S as Socket.IO Server
participant B as Peer B
A->>S: peerix:subscribe(namespace)
B->>S: peerix:subscribe(namespace)
A->>S: peerix:dispatch(namespace, payload)
S->>B: peerix:message(namespace, payload)
B->>S: peerix:unsubscribe(namespace)
Server Example
Your Socket.IO server should subscribe clients to namespaces and broadcast dispatched messages to other peers in the same namespace.
const { Server } = require('socket.io');
const io = new Server(8080, {
cors: { origin: '*' },
});
io.on('connection', (socket) => {
socket.on('peerix:subscribe', (namespace, callback) => {
socket.join(namespace);
callback();
});
socket.on('peerix:unsubscribe', (namespace, callback) => {
socket.leave(namespace);
callback();
});
socket.on('peerix:dispatch', (namespace, payload) => {
socket.broadcast.to(namespace).emit('peerix:message', namespace, payload);
});
});In this setup, each namespace acts like a signaling room. When one peer dispatches a signaling message, the server relays it to the other peers subscribed to that namespace.