-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
94 lines (70 loc) · 2.29 KB
/
server.js
File metadata and controls
94 lines (70 loc) · 2.29 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import express from 'express';
import { createServer } from "http";
import cors from 'cors';
import { Server } from "socket.io";
import ACTIONS from './src/Actions.js';
const app = express();
app.use(cors({
origin: ["http://localhost:5173", "http://127.0.0.1:5173", "http://localhost:5000"],
methods: ["GET", "POST"],
allowedHeaders: ["*"],
credentials: true
}));
app.use(express.static('dist'));
app.use((req,res,next)=>{
res.sendFile(path.join(__dirname,'dist','index.html'))
})
const server = createServer(app);
const io = new Server(server,{
cors: {
origin: ["http://localhost:5173","http://127.0.0.1:5173", "http://localhost:5000"], // Your React app's URL
methods: ["GET", "POST"],
allowedHeaders:["*"],
credentials:true
}
})
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(ACTIONS.JOIN,({roomid,username})=>{
userSocketMap[socket.id] = username
socket.join(roomid);
const clients = getAllConnectedClients(roomid);
clients.forEach(({socketID})=>{
io.to(socketID).emit(ACTIONS.JOINED,{
clients,
username,
socketID:socket.id
})
})
})
socket.on(ACTIONS.CODE_CHANGE, ({roomid,code}) => {
console.log('recieving',code)
socket.to(roomid).emit(ACTIONS.CODE_CHANGE,{code})
})
// socket.on(ACTIONS.SYNC_CODE, ({socketID,code}) => {
// console.log('recieving',code)
// socket.to(socketID).emit(ACTIONS.CODE_CHANGE,{code})
// })
socket.on('disconnecting',()=>{
const rooms = [...socket.rooms]
rooms.forEach((roomid)=>{
socket.in(roomid).emit(ACTIONS.DISCONNECTED,{
socketID:socket.id,
username:userSocketMap[socket.id],
})
})
delete userSocketMap[socket.id]
socket.leave()
})
})
const PORT= process.env.PORT || 5000;
server.listen(PORT,'0.0.0.0',()=>console.log(`served at http://localhost:${PORT}`))