| import express from 'express'; |
| import { createServer } from 'http'; |
| import { Server } from 'socket.io'; |
| import { fileURLToPath } from 'url'; |
| import { dirname, join } from 'path'; |
|
|
| const __filename = fileURLToPath(import.meta.url); |
| const __dirname = dirname(__filename); |
|
|
| const app = express(); |
| const httpServer = createServer(app); |
| const io = new Server(httpServer, { |
| cors: { |
| origin: "*", |
| methods: ["GET", "POST"] |
| } |
| }); |
|
|
| |
| app.use(express.static(join(__dirname, 'dist'))); |
|
|
| |
| app.get('*', (req, res) => { |
| res.sendFile(join(__dirname, 'dist', 'index.html')); |
| }); |
|
|
| |
| io.on('connection', (socket) => { |
| console.log('User connected:', socket.id); |
|
|
| socket.on('join-room', (roomId) => { |
| const room = io.sockets.adapter.rooms.get(roomId); |
| const numClients = room ? room.size : 0; |
|
|
| if (numClients < 10) { |
| socket.join(roomId); |
|
|
| |
| const otherUsers = []; |
| if (room) { |
| room.forEach(id => { |
| if (id !== socket.id) otherUsers.push(id); |
| }); |
| } |
|
|
| |
| socket.emit('all-users', otherUsers); |
|
|
| |
| |
|
|
| } else { |
| socket.emit('full'); |
| return; |
| } |
|
|
| |
| const updatedRoom = io.sockets.adapter.rooms.get(roomId); |
| io.to(roomId).emit('room-count', updatedRoom ? updatedRoom.size : 0); |
| }); |
|
|
| |
| socket.on('offer', ({ offer, to }) => { |
| io.to(to).emit('offer', { offer, from: socket.id }); |
| }); |
|
|
| socket.on('answer', ({ answer, to }) => { |
| io.to(to).emit('answer', { answer, from: socket.id }); |
| }); |
|
|
| socket.on('ice-candidate', ({ candidate, to }) => { |
| io.to(to).emit('ice-candidate', { candidate, from: socket.id }); |
| }); |
|
|
| |
| socket.on('caption', ({ text, userName, roomId }) => { |
| socket.to(roomId).emit('caption', { text, userName }); |
| }); |
|
|
| |
| socket.on('chat-message', ({ text, userName, roomId }) => { |
| socket.to(roomId).emit('chat-message', { text, userName }); |
| }); |
|
|
| |
| socket.on('user-info', ({ userName, roomId }) => { |
| |
| socket.to(roomId).emit('user-joined', { userName, callerID: socket.id }); |
| |
| socket.to(roomId).emit('user-info', { userName, id: socket.id }); |
| }); |
|
|
| socket.on('disconnecting', () => { |
| for (const room of socket.rooms) { |
| if (room !== socket.id) { |
| |
| const roomObj = io.sockets.adapter.rooms.get(room); |
| const count = roomObj ? roomObj.size - 1 : 0; |
| socket.to(room).emit('room-count', count); |
| socket.to(room).emit('user-disconnected', socket.id); |
| socket.to(room).emit('user-left', { userName: 'A user' }); |
| } |
| } |
| }); |
|
|
| socket.on('disconnect', () => { |
| console.log('User disconnected'); |
| }); |
| }); |
|
|
| |
| const PORT = process.env.PORT || 7860; |
|
|
| httpServer.listen(PORT, () => { |
| console.log(`Server running on port ${PORT}`); |
| }); |