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(() => {
  }, 1000)
  socket.on('data', (data) => {
  socket.on('end', () => { clearInterval(interval) })

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(() => {
  }, 250)
}, 3250)

output on client

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


  • 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());
    setTimeout(() => {
      socket.write("all done");
      setTimeout(() => {
      }, 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.


Upcoming Training