i have alread tried replacing announced ip with public url of my hosted website but that is of no use,
help me what should i do of announcec ip on deploying it
import express from ‘express’;
import fs from ‘fs’;
import path from ‘path’;
import http from ‘http’;
import { Server } from ‘socket.io’;
import mediasoup from ‘mediasoup’;
import axios from ‘axios’;
import os from ‘os’;
const app = express();
const port = 3000;
app.use(express.json());
const __dirname = path.resolve();
app.use(express.static(path.join(__dirname)));
app.get(‘/’, (req, res) => {
res.sendFile(path.join(__dirname, ‘home.html’));
});
app.get(‘/room/:roomNumber’, (req, res) => {
res.sendFile(path.join(__dirname, ‘room.html’));
});
const httpsServer = http.createServer(app);
httpsServer.listen(port, () => {
console.log('listening on port: ’ + port);
});
const io = new Server(httpsServer);
const connections = io.of(‘/mediasoup’);
let worker;
let rooms = {};
let peers = {};
let transports = ;
let producers = ;
let consumers = ;
// Function to get the public IP address
async function getPublicIp() {
try {
const response = await axios.get(‘https://api.ipify.org?format=json’);
console.log(‘Public IP:’, response.data.ip); // Debugging: Log IP
return response.data.ip;
} catch (error) {
console.error(‘Failed to get public IP:’, error);
return null;
}
}
// Create Mediasoup worker
const createWorker = async () => {
worker = await mediasoup.createWorker({
rtcMinPort: 2000,
rtcMaxPort: 2050,
});
console.log(worker pid ${worker.pid}
);
worker.on('died', error => {
console.error('mediasoup worker has died');
setTimeout(() => process.exit(1), 2000); // exit in 2 seconds
});
return worker;
};
const mediaCodecs = [
{
kind: ‘audio’,
mimeType: ‘audio/opus’,
clockRate: 48000,
channels: 2,
},
{
kind: ‘video’,
mimeType: ‘video/VP8’,
clockRate: 90000,
parameters: {
‘x-google-start-bitrate’: 1000,
},
},
];
// Initialize worker
createWorker();
connections.on(‘connection’, async socket => {
console.log(socket.id);
socket.emit(‘connection-success’, { socketId: socket.id });
const removeItems = (items, socketId, type) => {
items.forEach(item => {
if (item.socketId === socket.id) {
item[type].close();
}
});
items = items.filter(item => item.socketId !== socket.id);
return items;
};
socket.on('disconnect', () => {
console.log('peer disconnected');
const peer = peers[socket.id];
if (peer) {
consumers = removeItems(consumers, socket.id, 'consumer');
producers = removeItems(producers, socket.id, 'producer');
transports = removeItems(transports, socket.id, 'transport');
const { roomName } = peer;
rooms[roomName] = {
router: rooms[roomName].router,
peers: rooms[roomName].peers.filter(socketId => socketId !== socket.id),
};
delete peers[socket.id];
} else {
console.log('Socket ID not found in peers');
}
});
socket.on('joinRoom', async ({ roomName }, callback) => {
const router = await createRoom(roomName, socket.id);
peers[socket.id] = {
socket,
roomName,
transports: [],
producers: [],
consumers: [],
peerDetails: {
name: '',
isAdmin: false,
},
};
const rtpCapabilities = router.rtpCapabilities;
callback({ rtpCapabilities });
});
const createRoom = async (roomName, socketId) => {
let router;
let peersList = [];
if (rooms[roomName]) {
router = rooms[roomName].router;
peersList = rooms[roomName].peers || [];
} else {
router = await worker.createRouter({ mediaCodecs });
}
console.log(`Router ID: ${router.id}`, peersList.length);
rooms[roomName] = {
router,
peers: [...peersList, socketId],
};
return router;
};
socket.on('createWebRtcTransport', async ({ consumer }, callback) => {
const roomName = peers[socket.id].roomName;
const router = rooms[roomName].router;
const publicIp = await getPublicIp(); // Get public IP
if (!publicIp) {
callback({ error: 'Failed to get public IP' });
return;
}
createWebRtcTransport(router, publicIp).then(
transport => {
callback({
params: {
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters,
}
});
addTransport(transport, roomName, consumer);
},
error => {
console.log(error);
callback({ error: 'Failed to create WebRTC transport' });
}
);
});
const addTransport = (transport, roomName, consumer) => {
transports = [
...transports,
{ socketId: socket.id, transport, roomName, consumer }
];
peers[socket.id] = {
...peers[socket.id],
transports: [
...peers[socket.id].transports,
transport.id,
]
};
};
const addProducer = (producer, roomName) => {
producers = [
...producers,
{ socketId: socket.id, producer, roomName }
];
peers[socket.id] = {
...peers[socket.id],
producers: [
...peers[socket.id].producers,
producer.id,
]
};
};
const addConsumer = (consumer, roomName) => {
consumers = [
...consumers,
{ socketId: socket.id, consumer, roomName }
];
peers[socket.id] = {
...peers[socket.id],
consumers: [
...peers[socket.id].consumers,
consumer.id,
]
};
};
socket.on('getProducers', callback => {
const { roomName } = peers[socket.id];
let producerList = [];
producers.forEach(producerData => {
if (producerData.socketId !== socket.id && producerData.roomName === roomName) {
producerList = [...producerList, producerData.producer.id];
}
});
callback(producerList);
});
const informConsumers = (roomName, socketId, id) => {
console.log(`just joined, id ${id} ${roomName}, ${socketId}`);
producers.forEach(producerData => {
if (producerData.socketId !== socketId && producerData.roomName === roomName) {
const producerSocket = peers[producerData.socketId].socket;
producerSocket.emit('new-producer', { producerId: id });
}
});
};
const getTransport = (socketId) => {
const [producerTransport] = transports.filter(transport => transport.socketId === socketId && !transport.consumer);
return producerTransport.transport;
};
socket.on('transport-connect', ({ dtlsParameters }) => {
console.log('DTLS PARAMS... ', { dtlsParameters });
getTransport(socket.id).connect({ dtlsParameters });
});
socket.on('transport-produce', async ({ kind, rtpParameters, appData }, callback) => {
const producer = await getTransport(socket.id).produce({
kind,
rtpParameters,
});
const { roomName } = peers[socket.id];
addProducer(producer, roomName);
informConsumers(roomName, socket.id, producer.id);
console.log('Producer ID: ', producer.id, producer.kind);
producer.on('transportclose', () => {
console.log('transport for this producer closed');
producer.close();
});
callback({
id: producer.id,
producersExist: producers.length > 1 ? true : false
});
});
socket.on('transport-recv-connect', async ({ dtlsParameters, serverConsumerTransportId }) => {
console.log(`DTLS PARAMS: ${dtlsParameters}`);
const consumerTransport = transports.find(transportData => (
transportData.consumer && transportData.transport.id == serverConsumerTransportId
)).transport;
await consumerTransport.connect({ dtlsParameters });
});
socket.on('consume', async ({ rtpCapabilities, remoteProducerId, serverConsumerTransportId }, callback) => {
try {
const { roomName } = peers[socket.id];
const router = rooms[roomName].router;
let consumerTransport = transports.find(transportData => (
transportData.consumer && transportData.transport.id === serverConsumerTransportId
));
if (!consumerTransport) {
consumerTransport = await createWebRtcTransport(router, await getPublicIp());
consumerTransport.on('close', () => {
console.log('transport closed');
});
}
const consumer = await consumerTransport.transport.consume({
producerId: remoteProducerId,
rtpCapabilities,
paused: true,
});
consumer.on('transportclose', () => {
console.log('transport for this consumer closed');
socket.emit('producer-closed', { remoteProducerId });
consumerTransport.close();
transports = transports.filter(transportData => transportData.transport.id !== consumerTransport.transport.id);
consumer.close();
consumers = consumers.filter(consumerData => consumerData.consumer.id !== consumer.id);
});
addConsumer(consumer, roomName);
const params = {
id: consumer.id,
producerId: remoteProducerId,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
serverConsumerId: consumer.id,
};
callback({ params });
} catch (error) {
console.log(error.message);
callback({ params: { error } });
}
});
socket.on('consumer-resume', async ({ serverConsumerId }) => {
console.log('consumer resume');
const { consumer } = consumers.find(consumerData => consumerData.consumer.id === serverConsumerId);
await consumer.resume();
});
});
const createWebRtcTransport = async (router, publicIp) => {
return new Promise(async (resolve, reject) => {
try {
const webRtcTransport_options = {
listenIps: [
{
ip: ‘0.0.0.0’,
announcedIp: publicIp, // Use public IP here
}
],
enableUdp: true,
enableTcp: true,
preferUdp: true,
};
let transport = await router.createWebRtcTransport(webRtcTransport_options);
console.log(`transport id: ${transport.id}`);
transport.on('dtlsstatechange', dtlsState => {
if (dtlsState === 'closed') {
transport.close();
}
});
transport.on('close', () => {
console.log('transport closed');
});
resolve(transport);
} catch (error) {
console.error('Failed to create WebRTC transport:', error); // Improved error logging
reject(error);
}
});
};