2013-01-04 01:45:57 -05:00
|
|
|
var net = require('net')
|
|
|
|
, EventEmitter = require('events').EventEmitter
|
|
|
|
, util = require('util')
|
|
|
|
, assert = require('assert')
|
|
|
|
, Client = require('./client')
|
|
|
|
|
|
|
|
module.exports = Server;
|
|
|
|
|
2013-01-07 23:36:14 -05:00
|
|
|
function Server() {
|
2013-01-04 01:45:57 -05:00
|
|
|
EventEmitter.call(this);
|
|
|
|
|
|
|
|
this.playerCount = 0
|
|
|
|
|
2013-01-04 20:22:19 -05:00
|
|
|
this.socketServer = null;
|
2013-01-04 01:45:57 -05:00
|
|
|
this.cipher = null;
|
|
|
|
this.decipher = null;
|
2013-01-04 20:22:19 -05:00
|
|
|
this.clients = {};
|
2013-01-04 01:45:57 -05:00
|
|
|
}
|
|
|
|
util.inherits(Server, EventEmitter);
|
|
|
|
|
|
|
|
Server.prototype.listen = function(port, host) {
|
|
|
|
var self = this;
|
2013-01-04 20:22:19 -05:00
|
|
|
var nextId = 0;
|
|
|
|
self.socketServer = net.createServer();
|
|
|
|
self.socketServer.on('connection', function(socket) {
|
2013-01-07 23:36:14 -05:00
|
|
|
var client = new Client(true);
|
2013-01-04 20:22:19 -05:00
|
|
|
client.id = nextId++;
|
|
|
|
self.clients[client.id] = client;
|
2013-01-04 01:45:57 -05:00
|
|
|
client.on('error', function(err) {
|
|
|
|
self.emit('error', err);
|
|
|
|
});
|
|
|
|
client.on('end', function() {
|
2013-01-04 20:22:19 -05:00
|
|
|
delete self.clients[client.id];
|
2013-01-04 01:45:57 -05:00
|
|
|
this.playerCount -= 1;
|
|
|
|
});
|
|
|
|
this.playerCount += 1;
|
2013-01-04 20:55:53 -05:00
|
|
|
client.setSocket(socket);
|
|
|
|
self.emit('connection', client);
|
2013-01-04 01:45:57 -05:00
|
|
|
});
|
2013-01-04 20:22:19 -05:00
|
|
|
self.socketServer.on('error', function(err) {
|
2013-01-04 01:45:57 -05:00
|
|
|
self.emit('error', err);
|
|
|
|
});
|
2013-01-04 20:22:19 -05:00
|
|
|
self.socketServer.on('close', function() {
|
|
|
|
self.emit('close');
|
2013-01-04 01:45:57 -05:00
|
|
|
});
|
2013-01-04 20:22:19 -05:00
|
|
|
self.socketServer.on('listening', function() {
|
2013-01-04 01:45:57 -05:00
|
|
|
self.emit('listening');
|
|
|
|
});
|
2013-01-04 20:22:19 -05:00
|
|
|
self.socketServer.listen(port, host);
|
|
|
|
};
|
|
|
|
|
|
|
|
Server.prototype.close = function() {
|
|
|
|
var client;
|
|
|
|
for(var clientId in this.clients) {
|
|
|
|
client = this.clients[clientId];
|
2013-01-04 20:55:53 -05:00
|
|
|
client.end('ServerShutdown');
|
2013-01-04 20:22:19 -05:00
|
|
|
}
|
|
|
|
this.socketServer.close();
|
2013-01-04 01:45:57 -05:00
|
|
|
};
|