-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (49 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
53
54
55
56
57
58
59
60
61
62
63
64
var express = require('express')
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var names = {};
app.use(express.static('dist'));
const port = process.env.PORT || 3000;
http.listen(port, () => {
console.log('listening on *:'+port);
});
io.on('connection', (socket) => {
socket.on('message', (message) => {
const room = getRoom(socket);
if(room) {
const isBinary = message.attachment !== null;
if(isBinary) {
socket.emit('binaryComing', true);
}
socket.binary(isBinary).to(room).emit('message', {sender: names[socket.id], ...message});
if(isBinary) {
socket.emit('binaryComing', false);
}
}
});
socket.on('joinRoom', ({room, user}) => {
names[socket.id] = user;
socket.join(room);
sendPresence(room);
});
socket.on('disconnecting', () => {
const room = getRoom(socket);
delete names[socket.id];
sendPresence(room, -1);
});
});
function getRoom(socket) {
const rooms = Object.keys(socket.rooms);
if(typeof rooms[1] !== 'undefined') return rooms[1];
return false;
}
function sendPresence(room, countDiff = 0) {
const data = io.sockets.adapter.rooms[room];
if(typeof io.sockets.adapter.rooms[room] === 'undefined') return false;
const users = Object.keys(data.sockets).map((socketId) => names[socketId]);
io.to(room).emit('presence', {
count: data.length + countDiff,
users
});
}