-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (41 loc) · 1.44 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
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, 'public')));
const users = {};
const get_users = (sid) => {
var t_users = [];
for (var key in users) {
if (key != sid) {
t_users.push(users[key].charAt(0).toUpperCase() + users[key].slice(1));
}
}
if (t_users.length == 0) {
return "-";
}
return t_users.join(', ');
};
io.on('connection', socket => {
socket.on('new-user-join', user => {
users[socket.id] = user;
socket.broadcast.emit('user-joined', user);
io.to(socket.id).emit('recevied_active_users', get_users(socket.id));
});
socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, user: users[socket.id] });
});
socket.on('disconnect', message => {
socket.broadcast.emit('left', { message: message, user: users[socket.id] });
delete users[socket.id];
io.to(socket.id).emit('recevied_active_users', get_users(socket.id));
});
socket.on('get_users', message => {
io.to(socket.id).emit('recevied_active_users', get_users(socket.id));
});
})
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));