-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
440 lines (352 loc) · 13.9 KB
/
server.js
File metadata and controls
440 lines (352 loc) · 13.9 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
* Node World
*
* by Assaf Koss.
*
* This is an interactive virtual game-world erver
* that saves to database, but queries it as little
* as possible.
*
* All the code is intended to be readable and simple,
* even at the expense of some functionality and efficiency.
*
* Naming conventions are short and reflect purpose.
*
* Functions are limited to about a hundred lines.
*
* Comments describe logic, for quick overviewing of functions.
*
* Best viewed in a modern code editor with Code Folding.
*
* Best edited with the assistance of JSHint.
*
* Composed with Sublime Text 3 with Code Folding, "tab_size": 2,
* and "translate_tabs_to_spaces": true.
*
* References for anything MongoDB in NodeJS:
* http://mongodb.github.io/node-mongodb-native/api-generated/collection.html
*
* Quick testing of NodeJS functionality:
* http://www.node-console.com/script/code
*/
//*** SERVER VARIABLES ***//
var ip = process.env.OPENSHIFT_DIY_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_DIY_PORT || 8080;
// var keyName = 'GameTest'; // Cookie name. Defaults to 'connect.sid'.
// var secret = '6edthsej75en43g35u563t345'; // Cookie pass.
////// The command character is the one character that messages are parsed for. //////
////// It is ignored if the following character is the same! //////
////// If sent by itself, it will reply with the help command. //////
cmdChar = '.';
nl = '\n'; // New line.
serverClosed = false;
// var cookieParser = express.cookieParser(secret);
// var cookie = require('cookie');
// var sessionStore = new connect.middleware.session.MemoryStore();
// *** //
//*** MODULE DEPENDENCIES ***//
var domain = require('domain');
var express = require('express');
var routes = require('./routes');
var http = require('http');
var app = express();
var connect = require('connect');
var server = http.createServer(app);
io = require('socket.io').listen(server, {
// Socket Server Options.
// 'close timeout' : 60, // Seconds to re-open the connection, after client disconnect.
'log level' : 1, // Recommended 1 for production.
'transports' : ['xhr-polling']
});
// Recomended settings for production.
io.enable('browser client minification'); // send minified client
io.enable('browser client etag'); // apply etag caching logic based on version number
io.enable('browser client gzip'); // gzip the file
/* Enable all transports.
io.set('transports', [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
]);
*/
/* Only HTTP protocol currently (16.2.2014) supported with OpenShift.
// IRC Server, to join world chat.
var ircUsers = {};
var messageStream = require('irc-message-stream'); // Parser for IRC protocol.
var net = require('net');
var irc = net.createServer(function (client) {
console.log('IRC Client connected.');
console.log(client);
var ircUser = {};
// The user has a reference to its' own socket.
ircUser.socket = client;
client.on('error', function(err) {
console.log('IRC Server Error:' + nl + err.stack);
});
client.on('end', function() {
console.log('IRC Client disconnected.');
});
client.on('close', function() {
console.log('IRC Server is down.');
});
var stream = new messageStream();
stream.on("data", function(message) {
console.log(message);
switch (message.command) {
case 'NICK':
ircUser.nickname = message.params[0];
ircUsers[ircUser.nickname] = ircUser;
break;
case 'USER':
// ircUser.ident = message.params[0];
// ircUser.realname = message.params[3];
break;
case 'PRIVMSG':
var target = message.params[0];
var msg = message.params[1];
break;
}
});
client.write('TEST MESSAGE FROM SERVER!\r\n');
client.pipe(stream);
});
// OpenShift allows ports in range 15000 - 35530.
var ircPort = 20000;
irc.listen(ircPort, ip, function() {
console.log('IRC Server listening on port ' + ircPort + ' for IP ' + ip + '.');
});
*/
// Constructors & Messages.
constructor = require('./constructors.js');
format = constructor.format; // Global, for quick text formatting.
// World Functionality Modules.
command = require('./commands.js');
// *** //
//*** APP SET/ENGINE/MIDDLEWARE/GET ***//
app.set('views', 'views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
// app.use(cookieParser);
// app.use(express.session({ store: sessionStore, signed: true,
// cookie: { httpOnly: true }, secret: secret, key: keyName }));
app.use(app.router);
app.use('/public', express.static('public'));
// Default index page.
app.get('/', routes.index);
//*** ERROR PAGES ***//
// Respond with this, when any error occures.
app.use(function(err, req, res, next){
res.status(err.status || 500);
if (req.accepts('html')) {
// res.render('500', { error: err });
res.send(err.message);
return;
}
// default to plain-text. send()
res.type('txt').send(err.message);
});
// 404 is not actually an error, but a last choice use(), after nothing else matched.
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
//res.render('404', { url: req.url });
res.send('<b>404 Page Not Found!</b>');
return;
}
// default to plain-text. send()
res.type('txt').send('404 Page Not Found!');
});
// Trigger errors for testing: //
app.get('/404', function(req, res, next){
next();
});
app.get('/403', function(req, res, next){
var err = new Error('403 Not Allowed!');
err.status = 403;
next(err);
});
app.get('/500', function(req, res, next){
next(new Error('500 Server Error!'));
});
// *** //
// *** //
//*** WORLD OBJECT ***//
// The world object holds all necessary server-side (off DB memory) data.
world = {};
// Set (or empty) the world object properties;
setWorld = constructor.world;
setWorld(); // Call the function, for the first time.
// *** //
//*** DATABASE OPEN CONNECTION & SOCKET LISTEN ***//
var MongoClient = require('mongodb').MongoClient;
db = {};
usersdb = {};
targetsdb = {};
mapsdb = {};
worlddb = {};
var dbAddress = 'mongodb://127.0.0.1:27017/nodeworld'; // db name is 'dyi' for production.
// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
dbAddress = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
process.env.OPENSHIFT_APP_NAME;
}
MongoClient.connect(dbAddress, function(err, db) {
if (err) {
console.log(err);
}
// Collections:
usersdb = db.collection('users'), // Registered players.
targetsdb = db.collection('targets'), // Objects, NPCs, MOBs, Animals, Items, and the rest.
mapsdb = db.collection('maps'); // Maps in Text clients, and Zones in 2D & 3D clients.
// Including Rooms (Text client) and Areas (2D & 3D clients).
worlddb = db.collection('world'); // World settings and configurations.
// Ensure Indexes! Indexing on '_id' is both automatic and 'unique', already.
usersdb.ensureIndex({ 'account.username': 1 },
{ 'background': true, 'unique': true }, function (err) {
if (err) {
console.log(err);
}
}); // Usernames are unique!
// Load world configurations from DB or create them.
worlddb.findOne({}, function (err, config) {
if (err) {
console.log(err);
return;
}
if (!config) {
console.log('No world config, yet. Loading default configurations...');
command.configureWorld();
return;
}
world.config = config; // Apply into world object.
console.log('World configuration loaded from database.');
});
// Listen.
server.listen(port, ip, function () {
console.log('Express & WebSocket server listening on port ' + port + ' for IP ' + ip + '.');
});
// mongoClient.close(); // No need to close connection manually,
// since only the server connects once, at any time.
});
// *** //
// Return a timestamp of '<hh:mm:ss> '.
Timestamp = function () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Make sure each is 2 digits, always.
hours = ( hours < 10 ? '0' + hours : hours );
minutes = ( minutes < 10 ? '0' + minutes : minutes );
seconds = ( seconds < 10 ? '0' + seconds : seconds );
var timestamp = '<' + hours + ':' + minutes + ':' + seconds + '> ';
return timestamp;
};
// Client connected to server.
io.sockets.on('connection', function (socket) {
// Server is closed.
if (serverClosed) {
// Kick socket.
socket.emit('info', format.bold('Server is closed!'));
socket.disconnect();
console.log('Connection attempt: Server closed!');
}
// Track number of connected users.
world.userCount += 1;
console.log(Timestamp() + world.userCount + ' user' + (world.userCount > 1 ? 's' : '') +
' connected to the server.');
// The user object that locally (per socket session) saves the logged-in user data from the DB.
var user = constructor.user(command.randomName(), socket); // Get a random name.
// Track all users in world.users object for general access and listing.
world.users[user.account.username] = user;
// Reset counter every minute.
var limitMessages = setTimeout(function () {
messageCount = 0;
limitMessages = null;
}, 60000);
// Track number of socket messages per minute.
var messageCount = 0;
// Welcome the new user.
socket.emit(constructor.welcome.type, constructor.welcome.message(user.player.name));
// Send cmdChar to user.
socket.emit('cmdChar', cmdChar);
// Inform everybody about the new user.
socket.broadcast.emit('info', command.fullNameID(user) + ' has joined.');
// Handle room and map loading, or creation, accordingly. Does a 'look', as well.
command.loadRoom(user);
// When a client socket emits/sends any message.
// NOTE: Parsing user input for commands
// is the sole responsibility of the client.
socket.on('message', function (message) {
// Flood protection.
messageCount += 1;
if (limitMessages !== null && messageCount >= 1000) {
// Limit socket messages to 1000 per minute.
socket.emit('error', 'Server command-flooding detected! Your commands are ignored for one minute.');
console.log(Timestamp() + 'User ' + command.fullNameID(user) + ' is command-flooding the server!');
return;
} else if (limitMessages === null) {
// Start timer.
limitMessages = setTimeout(function () {
messageCount = 0;
limitMessages = null;
}, 60000);
}
// Check for command character.
if (message.charAt(0) == cmdChar && message.charAt(1) != cmdChar) {
// Remove cmdChar from message.
message = message.slice(1);
// Every command message is handled on a new domain.
var curDomain = new domain.create();
// Catch error.
curDomain.on('error', function (err) {
console.log(Timestamp() + err.stack + nl);
socket.emit('error', format.bold('Command failed!') + format.newline + err.message + format.newline);
});
// Run the command.
curDomain.run(function () {
process.nextTick(function () {
command.handleCommands(message, user);
});
});
return;
}
// Default to chat message.
command.handleCommands('chat ' + message, user);
});
// When a client socket disconnects.
socket.on('disconnect', function () {
var strCoord = command.strPos(user.player.room);
// Remove myself from the room's and map's watchers.
world.watch[strCoord].splice(world.watch[strCoord].indexOf(user), 1);
world.watch[user.player.map].splice(world.watch[user.player.map].indexOf(user), 1);
// Update 'lastonline' if it's a registered user.
if (user.account.lastonline) {
user.account.lastonline = new Date();
}
// Immediate save to DB for registered users.
if (user.account.registered) {
command.saveUser(user);
}
// Inform all.
io.sockets.emit('info', command.fullNameID(user) + ' has left.');
delete world.users[user.account.username]; // Clean up the user reference from world object.
// Track number of connected users.
world.userCount -= 1;
console.log(Timestamp() + world.userCount + ' user' + (world.userCount > 1 ? 's' : '') +
' connected to the server.');
});
});
// Requests a check to save world changes to the DB, by intervals.
worldSaver = setInterval(command.saveWorld, 1000 * 10); // Milliseconds, so 1000 * 60 = 60 seconds.