Last active
July 31, 2019 11:48
-
-
Save isaacgr/7138c2fa57446aaaa9d19b34bb9d19fd to your computer and use it in GitHub Desktop.
A simple node tcp server/client with a message buffer stack to handle incoming data
This file contains 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 characters
const net = require('net') | |
// Message buffer class to handle incoming data | |
class MessageBuffer { | |
constructor(delimiter) { | |
this.delimiter = delimiter; | |
this.buffer = ""; | |
} | |
isFinished() { | |
if ( | |
this.buffer.length === 0 | |
|| this.buffer.indexOf(this.delimiter) === -1 | |
) { | |
return true; | |
} | |
return false; | |
} | |
push(data) { | |
this.buffer += data; | |
} | |
getMessage() { | |
const delimiterIndex = this.buffer.indexOf(this.delimiter); | |
if (delimiterIndex !== -1) { | |
const message = this.buffer.slice(0, delimiterIndex); | |
this.buffer = this.buffer.replace(message + this.delimiter, ""); | |
return message; | |
} | |
return null; | |
} | |
handleData() { | |
/** | |
* Try to accumulate the buffer with messages | |
* | |
* If the server isnt sending delimiters for some reason | |
* then nothing will ever come back for these requests | |
*/ | |
const message = this.getMessage(); | |
return message; | |
} | |
} | |
const server = new net.Server() | |
server.listen({host: '127.0.0.1', port: 9999}) | |
server.on('connection', (client) => { | |
client.write('{"name": "isaac",') | |
setTimeout(() => { | |
client.write('"age": "28"}\n{"name": "steve",') // simulate tcp fragmentation | |
}, 100) | |
}) | |
const client = new net.Socket() | |
client.connect(9999, '127.0.0.1') | |
let received = new MessageBuffer('\n') | |
client.on('data', (data) => { | |
received.push(data) | |
while(!received.isFinished()){ | |
const message = received.handleData() | |
console.log(JSON.parse(message)) | |
} | |
}) | |
client.on('close', () => { | |
console.log('connection closed') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment