Welcome to the Linux Foundation Forum!

Readable-Writable Streams: Duplex Example

The code examples for Duplex in Readable-Writable Streams does not appear to be matching the outputs shown. I can see the 3 beat outputs coming from socket.write('beat') on the server side and the ALL DONE coming from socket.write('all done') on the client but I cannot find the HELLO output. Is something missing from the client code

server code

'use strict'
const net = require('net')
net.createServer((socket) => {
  const interval = setInterval(() => {
    socket.write('beat')
  }, 1000)
  socket.on('data', (data) => {
    socket.write(data.toString().toUpperCase())
  })
  socket.on('end', () => { clearInterval(interval) })
}).listen(3000)

client code

'use strict'
const net = require('net')
const socket = net.connect(3000)

socket.on('data', (data) => {
  console.log('got data:', data.toString())
})

setTimeout(() => {
  socket.write('all done')
  setTimeout(() => {
    socket.end()
  }, 250)
}, 3250)

output on client

got data: HELLO
got data: beat
got data: beat
got data: beat
got data: ALL DONE

Comments

  • I tested running the code and I believe that the client code is missing a line.
    The output will only be correct if socket.write("hello"); is added before the first setTimeout block.

    "use strict";
    const net = require("net");
    const socket = net.connect(3000);
    
    socket.on("data", (data) => {
      console.log("got data:", data.toString());
    });
    
    socket.write("hello");
    setTimeout(() => {
      socket.write("all done");
      setTimeout(() => {
        socket.end();
      }, 250);
    }, 3250);
    

    Does anyone encounter the same behaviour?

  • That is what I did.

  • thanks @seetdev - you're correct about the missing line, thanks for letting us know

This discussion has been closed.

Categories

Upcoming Training