-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
49 lines (41 loc) · 1.22 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
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
// Serve static files from the "public" directory
app.use(express.static('public'));
// Store the connected users
const users = {};
io.on('connection', (socket) => {
let userName;
socket.on('join', (name) => {
if (userName) {
// User changing username
const prevUserName = userName;
userName = name;
users[socket.id] = userName;
socket.broadcast.emit('userChange', { prevUserName, newUserName: userName });
} else {
// User joining for the first time
userName = name;
users[socket.id] = userName;
socket.broadcast.emit('userJoin', userName);
}
});
socket.on('leave', () => {
socket.broadcast.emit('userLeave', userName);
delete users[socket.id];
});
socket.on('message', (message) => {
io.emit('message', { user: users[socket.id], message: message });
});
socket.on('disconnect', () => {
if (userName) {
socket.broadcast.emit('userLeave', userName);
delete users[socket.id];
}
});
});
http.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});