-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
48 lines (39 loc) · 1.35 KB
/
sockets.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
var app = require('./app');
var httpServer = require('http').Server(app);
var io = require('socket.io')(httpServer);
var users = {};
//sockets
io.on('connection', function(socket){
console.log('a user connected');
socket.on('joinroom', function(username, room){
socket.room = room;
socket.join(room);
if(!users[room]){
users[room] = [];
}
if(users[room].indexOf(username) !== -1){
socket.emit('joinedroom', false);
}
else{
socket.username = username;
users[room].push(username);
io.sockets.in(room).emit('userchange', users[room]);
socket.emit('joinedroom', true);
}
});
socket.on('sendnote', function(instrument, pitch){
io.sockets.in(socket.room).emit('recievedata', socket.username, instrument, pitch);
});
socket.on('disconnect', function(){
console.log(socket.username + ' disconnected');
if(users[socket.room]){
var idx = users[socket.room].indexOf(socket.username);
if(idx != -1)
users[socket.room].splice(idx, 1);
io.sockets.in(socket.room).emit('userchange', users[socket.room]);
if(users[socket.room].length === 0)
delete users[socket.room];
}
});
});
module.exports = httpServer;