Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const WebSocket = require('ws');
- // Initialize a new WebSocket server on port 5001
- const PORT = process.env.PORT || 5001;
- const wss = new WebSocket.Server({ port: PORT });
- // This object will store rooms and the clients within them
- const rooms = {};
- console.log('Signaling server is running on port 5001');
- wss.on('connection', ws => {
- console.log('Client connected');
- // Handle messages from the client
- ws.on('message', message => {
- let data;
- try {
- data = JSON.parse(message);
- } catch (e) {
- console.error('Invalid JSON received:', message);
- return;
- }
- const { type, roomId, ...payload } = data;
- // Use a switch statement to handle different message types
- switch (type) {
- // When a user wants to join a room
- case "join_room":
- currentRoom = data.roomId;
- if (!rooms[currentRoom]) {
- rooms[currentRoom] = [];
- }
- rooms[currentRoom].push(ws);
- console.log(`Client joined room: ${currentRoom}`);
- // Notify the first peer that a second peer has joined
- if (rooms[currentRoom].length === 2) {
- rooms[currentRoom][0].send(JSON.stringify({ type: "peer_joined" }));
- }
- break;
- // Forwarding offer, answer, and candidate messages to the other client in the room
- case 'offer':
- case 'answer':
- case 'candidate': {
- console.log(`Forwarding message of type '${type}' in room ${roomId}`);
- const room = rooms[roomId];
- if (room) {
- // Send the message to every other client in the room
- room.forEach(client => {
- if (client !== ws && client.readyState === WebSocket.OPEN) {
- client.send(JSON.stringify({ type, ...payload }));
- }
- });
- }
- break;
- }
- default:
- console.warn(`Unknown message type received: ${type}`);
- }
- });
- // Handle client disconnection
- ws.on('close', () => {
- console.log('Client disconnected');
- const { roomId } = ws; // Get the roomId that was stored on the connection
- if (roomId && rooms[roomId]) {
- // Notify the other peer that their partner has left
- rooms[roomId].forEach(client => {
- if (client !== ws && client.readyState === WebSocket.OPEN) {
- client.send(JSON.stringify({ type: 'peer_left' }));
- }
- });
- // Remove the disconnected client from the room
- rooms[roomId] = rooms[roomId].filter(client => client !== ws);
- // If the room is now empty, delete it
- if (rooms[roomId].length === 0) {
- console.log(`Room ${roomId} is empty and has been deleted.`);
- delete rooms[roomId];
- }
- }
- });
- ws.on('error', (error) => {
- console.error('WebSocket error:', error);
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment