Last active
November 21, 2023 16:23
-
-
Save kieranja/8957906 to your computer and use it in GitHub Desktop.
Revisions
-
kieranja revised this gist
Apr 9, 2014 . No changes.There are no files selected for viewing
-
kieranja created this gist
Feb 12, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,63 @@ 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); }