Skip to content

Instantly share code, notes, and snippets.

@gireeshpunathil
Created March 1, 2018 08:50
Show Gist options
  • Save gireeshpunathil/ec92c57dd7dad808989401a96680c105 to your computer and use it in GitHub Desktop.
Save gireeshpunathil/ec92c57dd7dad808989401a96680c105 to your computer and use it in GitHub Desktop.
Full duplex data exchange between client and server without waiting for request-response cycle and with a custom event
var net = require('net')
const DELIM = '*'
const server = net.createServer((s) => {
s.setNoDelay(true)
s.on('data', (d) => {
if (d.includes(DELIM)) {
var index = d.indexOf(DELIM, 0)
while (d.length) {
const piece = d.slice(0, index)
s.write(piece.toString().toUpperCase())
s.write(DELIM)
d = d.slice(index + 1)
index = d.indexOf(DELIM, 0)
}
}
})
})
server.listen(() => {
const c = net.createConnection({ port: server.address().port}, () => {
})
c.setNoDelay(true)
c.on('data', (d) => {
if (d.includes(DELIM)) {
var index = d.indexOf(DELIM, 0)
while (d.length) {
c.emit('response', d.slice(0, index))
d = d.slice(index + 1)
index = d.indexOf(DELIM, 0)
}
}
})
c.on('response', (d) => {
console.log(`output: ${d.toString()}`)
})
setInterval(() => {
for (var i=0; i< 16; i++) {
const data = getModbus()
console.log('input: ' + data.toString())
c.write(data)
c.write(DELIM)
}
}, 100)
})
function getModbus() {
const buf = Buffer.alloc(10)
for (var i = 0; i< 10; i++)
buf[i] = [(97 + Math.round((Math.random() * 26)))]
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment