Webrtc connections require a signalling server to be created. This is a server that will be responsible for facilitating communication between peers, exchanging session information and negotiation of messages. Signalling does not handle the actual data transfer but is responsible for the peer discovery that allows them to setup a connection. To do this, we need node.js installed and websocket. You can download and install node.js on your computer from this link Download | Node.js (nodejs.org) . After installation open the command prompt. Run the following commands
mkdir webrtc-signaling-server
cd webrtc-signaling-server
npm init -y
The command “mkdir webrtc-signaling-server” creates a new folder that will be used for the server. We then enter the folder using the “cd webrtc-signaling-server” command. The last command “npm init -y” creates a basic node.js project in your user directory with some default values as shown in the figure below.
We can then install the dependencies “express” and “ws” by running the following command. "npm install express ws"
Inside the webrtc-signaling-server folder, create a new file and name it as “server.js”. This will be the script for the signalling server itself. It should look like the image below.
Open the server.js file for editing and we will begin by adding the following code.
Continuation of the server.js file
Continuation of server.js file.
The broadcast function iterates through all connected clients and sends the provided message to each client except the sender, ensuring that the message is only sent to other clients.
Continuation of server.js file
The full server script should look as shown below.
// server.js
'use strict';
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
// Store connected clients
const clients = new Set();
wss.on('connection', (ws) => {
console.log('Client connected');
clients.add(ws);
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
broadcast(message, ws);
});
ws.on('close', () => {
console.log('Client disconnected');
clients.delete(ws);
});
});
function broadcast(message, sender) {
clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Now that we have a basic signalling server, we can try running the server by running the following command. Make sure your terminal is working from the directory created earlier i.e. "webrtc-signaling-server." If not in the directory, run "cd webrtc-signaling-server"
node server.js
This will start the server. The firewall on your machine might require permission to use this server on your network as shown below.