-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (49 loc) · 1.77 KB
/
index.js
File metadata and controls
63 lines (49 loc) · 1.77 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
import { createServer } from 'http';
import express from 'express';
import { Server } from "socket.io";
import cors from 'cors';
import router from './router.js';
import { addUser, removeUser, getRoomUserList, getUser} from './service.js';
const app = express();
const server = createServer(app);
const io = new Server(server);
app.use(cors());
app.use(router);
io.on('connect', (socket) => {
socket.on('join', ({name, userId, course}) => {
//TODO: catch error
const user = addUser(userId, name, course);
if (user) {
const userList = getRoomUserList(user.roomId);
socket.join(user.roomId);
io.to(user.roomId).emit('getUserList', { users: userList });
io.to(user.roomId).emit('newMessage', {
context: name + " has joined the room",
from: "admin",
});
}
});
socket.on("sendMessage", ({context, from}) => {
const user = getUser(from);
io.to(user.roomId).emit("newMessage", {
context,
from: from,
});
});
socket.on('disconnected', (userId) => {
//TODO: remove current user
console.log(`${userId} has disconnected`)
const user = getUser(userId);
removeUser(userId);
if(user) {
const userList = getRoomUserList(user.roomId);
io.to(user.roomId).emit('newMessage', {
context: `${user.name} has left the room`,
from: "admin",
});
io.to(user.roomId).emit('getUserList', {roomId: user.roomId, users: userList});
}
//console.log(`${userId} has disconneted from room ${user.roomId}`)
})
});
server.listen(process.env.PORT || 5000, () => console.log(`Server has started.`));