2013-01-04 01:45:57 -05:00
|
|
|
var net = require('net')
|
|
|
|
, EventEmitter = require('events').EventEmitter
|
|
|
|
, util = require('util')
|
|
|
|
, protocol = require('./protocol')
|
|
|
|
, createPacketBuffer = protocol.createPacketBuffer
|
|
|
|
, parsePacket = protocol.parsePacket
|
|
|
|
|
|
|
|
module.exports = Client;
|
|
|
|
|
2013-01-07 23:36:14 -05:00
|
|
|
function Client(isServer) {
|
2013-01-04 01:45:57 -05:00
|
|
|
EventEmitter.call(this);
|
|
|
|
|
2013-01-07 23:36:14 -05:00
|
|
|
this.isServer = !!isServer;
|
2013-01-04 01:45:57 -05:00
|
|
|
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);
|
2013-01-04 21:57:17 -05:00
|
|
|
self.emit('packet', packet);
|
2013-01-04 01:45:57 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
self.socket.on('error', function(err) {
|
|
|
|
self.emit('error', err);
|
|
|
|
});
|
|
|
|
|
|
|
|
self.socket.on('close', function() {
|
2013-01-04 20:55:53 -05:00
|
|
|
self.emit('end', self._endReason);
|
2013-01-04 01:45:57 -05:00
|
|
|
});
|
2013-01-04 21:33:19 -05:00
|
|
|
|
|
|
|
self.socket.on('connect', function() {
|
|
|
|
self.emit('connect');
|
|
|
|
});
|
2013-01-04 01:45:57 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
Client.prototype.connect = function(port, host) {
|
|
|
|
var self = this;
|
2013-01-04 22:47:54 -05:00
|
|
|
self.setSocket(net.connect(port, host));
|
2013-01-04 01:45:57 -05:00
|
|
|
};
|
|
|
|
|
2013-01-04 20:55:53 -05:00
|
|
|
Client.prototype.end = function(reason) {
|
|
|
|
this._endReason = reason;
|
2013-01-04 01:45:57 -05:00
|
|
|
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);
|
|
|
|
};
|