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

  1. 'use strict'
  2. const net = require('net')
  3. net.createServer((socket) => {
  4. const interval = setInterval(() => {
  5. socket.write('beat')
  6. }, 1000)
  7. socket.on('data', (data) => {
  8. socket.write(data.toString().toUpperCase())
  9. })
  10. socket.on('end', () => { clearInterval(interval) })
  11. }).listen(3000)

client code

  1. 'use strict'
  2. const net = require('net')
  3. const socket = net.connect(3000)
  4.  
  5. socket.on('data', (data) => {
  6. console.log('got data:', data.toString())
  7. })
  8.  
  9. setTimeout(() => {
  10. socket.write('all done')
  11. setTimeout(() => {
  12. socket.end()
  13. }, 250)
  14. }, 3250)

output on client

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

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

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.

    1. "use strict";
    2. const net = require("net");
    3. const socket = net.connect(3000);
    4.  
    5. socket.on("data", (data) => {
    6. console.log("got data:", data.toString());
    7. });
    8.  
    9. socket.write("hello");
    10. setTimeout(() => {
    11. socket.write("all done");
    12. setTimeout(() => {
    13. socket.end();
    14. }, 250);
    15. }, 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.

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training