-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.js
53 lines (41 loc) · 1.21 KB
/
app.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
var path = require('path');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendfile('views/index.html');
});
var connections = {};
var numConnections = 0;
io.on('connection', function(socket) {
connections[socket.id] = socket;
numConnections ++;
socket.emit('setup', { socketId: socket.id });
console.log('user connected');
console.log(numConnections + ' users connected');
socket.on('disconnect', function(){
delete connections[socket.id];
numConnections --;
console.log('user disconnected');
console.log(numConnections + ' users connected');
});
socket.on('keyup', function(data) {
emitAll('stop', data);
});
socket.on('keydown', function(data) {
emitAll('start', data);
});
});
http.listen(process.env.PORT || 3000, function() {
console.log('listening on *:3000');
});
function emitAll(eventType, data) {
for (socketId in connections) {
if (connections.hasOwnProperty(socketId)) {
connections[socketId].emit(eventType, data)
}
}
}