-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (69 loc) · 2.07 KB
/
index.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
require(`dotenv`).config();
const express = require(`express`);
const http = require(`http`);
const socketIO = require(`socket.io`);
const app = express();
const server = http.Server(app);
const io = socketIO(server);
const users = new Map();
app.use(express.static(`${__dirname}/build`));
io.on(`connection`, socket => {
socket.once(`join`, ({ name, room }) => {
name = name && name.trim();
room = room && room.trim();
if (!name || !room) {
return socket.disconnect();
} else if (
[...users.values()].find(
user =>
user.room === room &&
user.name.toLowerCase() === name.toLowerCase()
)
) {
socket.emit(`name-taken`);
return socket.disconnect();
}
const user = {
id: socket.id,
name: name,
room: room,
};
socket.join(room);
users.set(socket.id, user);
io.to(room).emit(`user-connected`, {
id: socket.id,
name: name,
});
socket.emit(
`users`,
[...users.values()].filter(user => user.room === room)
);
});
socket.on(`message`, message => {
const user = users.get(socket.id);
message = message.trim();
if (user && message !== ``) {
if (message.length > 2000) {
socket.emit(`message`, message);
} else {
io.to(user.room).emit(`message`, {
message: message.trim(),
date: new Date(),
user: {
id: user.id,
name: user.name,
},
});
}
}
});
socket.on(`disconnect`, () => {
users.delete(socket.id);
io.emit(`user-disconnected`, socket.id);
});
});
const port = process.env.PORT || 5000;
server.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Listening: http://localhost:${port}`);
});