This repository was archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (44 loc) · 1.54 KB
/
index.js
File metadata and controls
51 lines (44 loc) · 1.54 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
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
const sanitizeHtml = require('sanitize-html');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
const roomData = {};
function uniqueName() {
return "Joe";
}
io.on('connection', (socket) => {
socket.emit('chat message', "[Please wait until you are connected...]")
const state = {};
socket.once('cohort_id', cohort => {
state.username = uniqueName();
state.cohort = cohort;
socket.join(state.cohort);
if (!!roomData[cohort]) {
roomData[cohort].numUsers += 1
} else {
roomData[cohort] = { numUsers: 1 };
}
io.in(state.cohort).emit('chat message', `[${state.username} has joined.]`);
socket.emit('chat message', `[You have been assigned the name "${state.username}".]`)
socket.emit('chat message', "[You have been connected to the chat room for cohort " + `${cohort}.]`);
socket.emit('chat message', `[There are ${roomData[cohort].numUsers} users in this chat room.]`);
})
socket.on('chat message', msg => {
if (!!state.cohort) {
io.in(state.cohort).emit('chat message', `<${state.username}> ${sanitizeHtml(msg)}`);
} else {
socket.emit('chat message', "[Message could not be sent.]")
}
});
socket.on('disconnect', () => {
if (!state.cohort) return
roomData[state.cohort].numUsers -= 1
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});