-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
58 lines (47 loc) · 1.58 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const express = require('express');
const app = express();
const http = require('http');
const path = require('path');
const { Server } = require('socket.io');
// const ACTIONS = require('./src/Actions');
const server = http.createServer(app);
const io = new Server(server);
const userSocketMap = {};
function getAllConnectedClients(roomId) {
return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
(socketId) => {
return{
socketId,
userName: userSocketMap[socketId],
}
})
}
io.on('connection', (socket) => {
console.log('Socket Connected', socket.id);
socket.on("join", ({ roomId, userName }) => {
userSocketMap[socket.id] = userName;
socket.join(roomId);
const clients = getAllConnectedClients(roomId);
console.log(clients);
clients.forEach(({ socketId }) => {
io.to(socketId).emit("joined", {
clients,
userName,
socketId: socket.id,
});
});
});
socket.on("disconnecting", () => {
const rooms = [...socket.rooms];
rooms.forEach((roomId) => {
socket.in(roomId).emit('disconnected', {
socketId : socket.id,
userName : userSocketMap[socket.id]
})
})
delete userSocketMap[socket.id];
socket.leave();
})
})
const PORT = process.env.PORT || 1234;
server.listen(PORT, () => console.log(`listening on port ${PORT}!`))