-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
212 lines (183 loc) · 5.07 KB
/
server.js
File metadata and controls
212 lines (183 loc) · 5.07 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
var port = process.env.PORT || 5000;
console.log("Listening on port " + port);
var http = require('http')
var express = require('express'), app = express();
var morgan = require('morgan'); //http logger module
var compression = require('compression')
var server = http.createServer(app).listen(port);
var jade = require('jade');
var io = require('socket.io').listen(server);
var os = require('os');
var redis = require("redis");
var redisClient = redis.createClient();
var lzwCompress = require('lzwcompress');
var compressor = require('node-minify');
var localConnectedClients = 0;
var clients = {};
var netUsage = 0;
//compress all JS into one file on startup
new compressor.minify({
type: 'uglifyjs',
fileIn: ['public/alertify.min.js',
'public/jquery.hammer.min.js',
'public/lzwCompress.js',
'public/draw.js'
],
fileOut: 'public/draw.min.js',
callback: function(err, min){
if (err){
console.log(err);
}
}
});
//compress css
new compressor.minify({
type: 'clean-css',
fileIn: ['public/alertify.core.css',
'public/alertify.default.css',
'public/style.css'
],
fileOut: 'public/style.min.css',
callback: function(err, min){
if(err){
console.log(err);
}
}
});
app.use(compression())
app.use(express.static(__dirname + '/public', {maxAge: 60*60*24*1000}));
app.use(morgan('combined'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout: false });
app.enable('trust proxy');
/* Main 'lobby' canvas */
app.get('/', function(req, res){
res.render('main.jade');
});
/* User canvas */
app.get("/c/:canvasname", function (req, res, next) {
res.render('main.jade', {canvasName: req.params.canvasname});
});
redisClient.on("error", function(err){
console.log("Redis Error: " + err);
});
//set client connection key if not exists
redisClient.setnx("clientcount", 0);
io.sockets.on('connection', function(socket){
localConnectedClients += 1;
redisClient.incr("clientcount");
socket.on('drawActionHistory', function(data){
//client has asked for all the draw action history.
var drawActions = [];
var key = "drawactions:"+data.canvasName;
redisClient.lrange(key, 0, -1, function(err, replies){
if(err){
console.log("Error fetching draw history key: " + key);
return;
}
replies.forEach(function(reply, i){
drawActions.push(JSON.parse(reply));
});
//compress drawaction history data
var compressedActions = lzwCompress.pack(drawActions)
//send it
socket.emit('drawActionHistory', compressedActions);
//increment netusage tracker.
netUsage += sizeof(compressedActions);
});
});
socket.on('mousemove', function(data){
if(data.id in clients){
var client = clients[data.id];
if(data.drawing){
var drawAction = {
fromX: client.x,
fromY: client.y,
toX: data.x,
toY: data.y,
color: data.color
};
var key = "drawactions:"+data.canvasName;
redisClient.rpush(key, JSON.stringify(drawAction));
}
} else {
//initilise a new client
var newClient = {
id: data.id
};
clients[data.id] = newClient;
}
clients[data.id].x = data.x;
clients[data.id].y = data.y;
netUsage += sizeof(data) * localConnectedClients;
socket.broadcast.emit('moving', data);
});
socket.on('chatmessage', function(data){
netUsage += sizeof(data) * localConnectedClients;
//take out possible tags.
data.message = data.message.replace(/(<([^>]+)>)/ig,"");
//limit chat message length.
if (data.message.length <= 135) {
socket.broadcast.emit('chatmessage', {
user: data.user,
message: data.message
});
}
});
socket.on('stats', function(id){
var multi = redisClient.multi();
var data = {
load1: (os.loadavg()[0]).toFixed(2),
netUsageKB: (netUsage / 1000).toFixed(1),
nodeConnections: localConnectedClients
};
/*
multi.llen("drawactions", function(err, reply){
data['drawStackSize'] = reply;
});
*/
multi.get('clientcount', function(err, reply){
data['globalConnectedClients'] = reply;
});
multi.lastsave(function(err, reply){
var now = (new Date().getTime()) / 1000;
data['lastStateSave'] = ((now - reply) / 60).toFixed(1);
});
multi.exec(function(err, replies){
socket.emit('stats', data);
netUsage += sizeof(data);
});
});
socket.on('ping', function(data){
socket.emit('pong');
});
socket.on('disconnect', function() {
localConnectedClients -= 1;
redisClient.decr("clientcount");
});
});
/**
* Get the estimated size of an object in bytes
*/
function sizeof(object) {
var objectList = [];
var stack = [object];
var bytes = 0;
while (stack.length) {
var value = stack.pop();
if (typeof value === 'boolean' ) {
bytes += 4;
} else if (typeof value === 'string') {
bytes += value.length * 2;
} else if (typeof value === 'number') {
bytes += 8;
} else if (typeof value === 'object' && objectList.indexOf( value ) === -1) {
objectList.push(value);
for(var i in value) {
stack.push(value[i]);
}
}
}
return bytes;
}