node-minecraft-protocol/lib/server.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

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
this.socketServer = null;
2013-01-04 01:45:57 -05:00
this.cipher = null;
this.decipher = null;
this.clients = {};
2013-01-04 01:45:57 -05:00
}
util.inherits(Server, EventEmitter);
Server.prototype.listen = function(port, host) {
var self = this;
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);
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() {
delete self.clients[client.id];
2013-01-04 01:45:57 -05:00
this.playerCount -= 1;
});
this.playerCount += 1;
client.setSocket(socket);
self.emit('connection', client);
2013-01-04 01:45:57 -05:00
});
self.socketServer.on('error', function(err) {
2013-01-04 01:45:57 -05:00
self.emit('error', err);
});
self.socketServer.on('close', function() {
self.emit('close');
2013-01-04 01:45:57 -05:00
});
self.socketServer.on('listening', function() {
2013-01-04 01:45:57 -05:00
self.emit('listening');
});
self.socketServer.listen(port, host);
};
Server.prototype.close = function() {
var client;
for(var clientId in this.clients) {
client = this.clients[clientId];
client.end('ServerShutdown');
}
this.socketServer.close();
2013-01-04 01:45:57 -05:00
};