Skip to content

Instantly share code, notes, and snippets.

@kieranja
Last active November 21, 2023 16:23
Show Gist options
  • Save kieranja/8957906 to your computer and use it in GitHub Desktop.
Save kieranja/8957906 to your computer and use it in GitHub Desktop.
Simple NodeJS client
function Client(ip, port, no_delay) {
this.ip = ip;
this.port = port;
this.no_delay = no_delay || true;
this.encoding = "utf8";
}
Client.prototype.init = function(new_payload_callback_fn) {
// Connect to main server.
this.connection = this.networking.createConnection(this.port, this.ip);
var buffer = '';
this.connection.on("data", function(data) {
// With all incoming data append it onto the buffer variable
buffer += data;
// Check for the terminator, if it exists we get the position (0 based)
var index = buffer.indexOf("\r\n");
// If there is a terminator in this payload, we need to process it.
while (index > -1) {
// so, the new buffer was added on, so if
// the previous was {"kiera
// and the new added n":"my name"}\r\n {"another\r\n
// then we now have a full JSON payload, which means we can treat it so
// however, the next payload had the start of another message too, which is not yet
// complete, so we need to pluck out the one which is complete. 0="{" to 23="n", so
// that is what string will contain.
var string = buffer.substr(0, d_index);
// As it's a valid JSON payload, let's parse it.
var json = JSON.parse(string);
// Invoke callback - and send through the JSON.
new_payload_callback_fn(json);
// set it to where we left off - we need to flush the message we've just processed,
// and set it to the start of the next., as the index was 0 based, index+1 will do that.
buffer = buffer.substr(index + 1);
// now if we find another message in here, (as indexof only returns the first)
// then this loop can be reset and the process can restart!
index = buffer.indexOf("\r\n");
}
});
}
var c = new Client('8080', 'localhost');
// start processing.
c.init(processMessage);
function processMessage(json) {
console.log("Recieved JSON:");
console.log(json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment