-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (68 loc) · 2.28 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
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
const http = require('http');
const express = require('express');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server);
const { addUser, removeUser, getUser, listUsersInRoom } = require('./users');
app.use(cors());
app.get('/', (req, res) => {
res.send({ response: 'Server is up and running.' }).status(200);
});
// Specify socket for user
io.on('connection', (socket) => {
console.log('New connection');
socket.on('join-room', ({ name, roomId, peerId }, callback) => {
const { error, user } = addUser({
id: socket.id,
name,
roomId,
peerId,
});
if (error) callback(error);
socket.emit('message', {
user: '',
text: 'You joined the room.',
sentAt: new Date().toJSON().slice(11, 16),
});
socket.broadcast.to(user.roomId).emit('message', {
user: '',
text: `${user.name} has joined.`,
sentAt: new Date().toJSON().slice(11, 16),
});
socket.to(user.roomId).broadcast.emit('user-connected', user.peerId);
socket.join(user.roomId);
io.to(user.roomId).emit('roomData', {
roomId: user.roomId,
users: listUsersInRoom(user.roomId),
});
callback();
});
socket.on('send-message', (message, callback) => {
const user = getUser(socket.id);
io.to(user.roomId).emit('message', {
user: user.name,
text: message,
sentAt: new Date().toJSON().slice(11, 16),
});
callback();
});
socket.on('disconnect', () => {
const user = removeUser(socket.id);
if (user) {
socket
.to(user.roomId)
.broadcast.emit('user-disconnected', user.peerId);
io.to(user.roomId).emit('message', {
user: '',
text: `${user.name} has left.`,
});
io.to(user.roomId).emit('roomData', {
roomId: user.roomId,
users: listUsersInRoom(user.roomId),
});
}
});
});
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));