add callback to write (socket.write *is* async) fix #168

This commit is contained in:
Romain Beaumont 2015-05-18 19:01:23 +02:00
parent e2519f0b9f
commit 6446b205f0
3 changed files with 41 additions and 22 deletions

View File

@ -156,7 +156,12 @@ Client.prototype.end = function(reason) {
this.socket.end();
};
Client.prototype.write = function(packetId, params) {
function noop(err) {
if(err) throw err;
}
Client.prototype.write = function(packetId, params, cb) {
cb = cb || noop;
if(Array.isArray(packetId)) {
if(packetId[0] !== this.state)
return false;
@ -175,9 +180,9 @@ Client.prototype.write = function(packetId, params) {
debug("writing packetId " + that.state + "." + packetName + " (0x" + packetId.toString(16) + ")");
debug(params);
var out = that.encryptionEnabled ? new Buffer(that.cipher.update(buffer), 'binary') : buffer;
that.socket.write(out);
that.socket.write(out,cb);
return true;
}
};
var buffer = createPacketBuffer(packetId, this.state, params, this.isServer);
if(this.compressionThreshold >= 0 && buffer.length >= this.compressionThreshold) {

View File

@ -125,9 +125,12 @@ function createServer(options) {
}
client.once([states.STATUS, 0x01], function(packet) {
client.write(0x01, {time: packet.time});
client.write(0x01, {time: packet.time},function(err){
if(err)
throw err;
client.end();
});
});
client.write(0x00, {response: JSON.stringify(response)});
}
@ -214,7 +217,9 @@ function createServer(options) {
}
//client.write('compress', { threshold: 256 }); // Default threshold is 256
//client.compressionThreshold = 256;
client.write(0x02, {uuid: client.uuid, username: client.username});
client.write(0x02, {uuid: client.uuid, username: client.username},function(err){
if(err)
throw err;
client.state = states.PLAY;
loggedIn = true;
startKeepAlive();
@ -227,6 +232,7 @@ function createServer(options) {
server.playerCount -= 1;
});
server.emit('login', client);
});
}
});
server.listen(port, host);
@ -297,12 +303,14 @@ function createClient(options) {
serverHost: host,
serverPort: port,
nextState: 2
});
},function(err){
if(err)
throw err;
client.state = states.LOGIN;
client.write(0x00, {
username: client.username
});
});
}
function onCompressionRequest(packet) {
@ -362,8 +370,11 @@ function createClient(options) {
client.write(0x01, {
sharedSecret: encryptedSharedSecretBuffer,
verifyToken: encryptedVerifyTokenBuffer,
});
},function(err){
if(err)
throw err;
client.encryptionEnabled = true;
});
}
}
}

View File

@ -37,9 +37,12 @@ function ping(options, cb) {
serverHost: host,
serverPort: port,
nextState: 1
});
},function(err){
if(err)
throw err;
client.state = states.STATUS;
});
});
client.connect(port, host);
}