node-minecraft-protocol/lib/client.js
Andrew Kelley 1661ef3b4b API updates
* test passing: kicks clients that do not log in
 * index exports `Client` and `Server`
 * `createServer`: `options.keepAliveInterval` -> `options.kickTimeout`
 * `Client` event `end` includes `reason` argument
   - `LoginTimeout`
   - `KeepAliveTimeout`
   - `ServerShutdown`
 * `createClient`: Set `options.keepAlive` to `false` to disable sending
   keep alive packets
 * `Client`: `options.isServer` defaults to `false`.
2013-01-04 20:55:53 -05:00

65 lines
1.7 KiB
JavaScript

var net = require('net')
, EventEmitter = require('events').EventEmitter
, util = require('util')
, protocol = require('./protocol')
, createPacketBuffer = protocol.createPacketBuffer
, parsePacket = protocol.parsePacket
module.exports = Client;
function Client(options) {
EventEmitter.call(this);
options = options || {};
this.isServer = !!options.isServer;
this.socket = null;
this.encryptionEnabled = false;
this.cipher = null;
this.decipher = null;
}
util.inherits(Client, EventEmitter);
Client.prototype.setSocket = function(socket) {
var self = this;
self.socket = socket;
var incomingBuffer = new Buffer(0);
self.socket.on('data', function(data) {
if (self.encryptionEnabled) data = new Buffer(self.decipher.update(data), 'binary');
incomingBuffer = Buffer.concat([incomingBuffer, data]);
var parsed, packet;
while (true) {
parsed = parsePacket(incomingBuffer, self.isServer);
if (! parsed) break;
packet = parsed.results;
incomingBuffer = incomingBuffer.slice(parsed.size);
self.emit(packet.id, packet);
}
});
self.socket.on('error', function(err) {
self.emit('error', err);
});
self.socket.on('close', function() {
self.emit('end', self._endReason);
});
};
Client.prototype.connect = function(port, host) {
var self = this;
self.setSocket(net.connect(port, host, function() {
self.emit('connect');
}));
};
Client.prototype.end = function(reason) {
this._endReason = reason;
this.socket.end();
};
Client.prototype.write = function(packetId, params) {
var buffer = createPacketBuffer(packetId, params, this.isServer);
var out = this.encryptionEnabled ? new Buffer(this.cipher.update(buffer), 'binary') : buffer;
this.socket.write(out);
};