Skip to content

Instantly share code, notes, and snippets.

@yaegaki
Created July 14, 2015 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaegaki/ead3ee48aded4c9c07f8 to your computer and use it in GitHub Desktop.
Save yaegaki/ead3ee48aded4c9c07f8 to your computer and use it in GitHub Desktop.
Read Packet
/** Packet format
* 4 bytes data size (x)
* x bytes data
*/
var sb = new StreamBuffer();
var requireLength = 0;
var state = 0;
client.on('data', function (data) {
if (state == 0) {
requireLength = 4;
}
sb.update(data);
while (sb.canRead(requireLength)) {
var buf = sb.read(requireLength);
if (state == 0) {
requireLength = buf.readUInt32LE();
state = 1;
} else if (state == 1) {
console.log(buf); // data
state = 0;
} else {
break;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment