Duplex Streams

In notebook:
FrontEndMasters Networking and Streams
Created at:
backend Node JS JavaScript


in this case a is a duplex stream.

Echo server example of duplex stream

  //	****		echo.js		****

const net = require('net')
// net will create a duplex stream 
// for every network connection
net.createServer(function (stream) {
  stream.pipe(stream) // you can pipe a stream into itself
  // so this will not create an infinite loop, it's decoupled
}).listen(5000) // ☛  listen...

Now it will split back the same string that you send to it.

This is a great way to demo sockets, async handling in the runtime.

Let's make an echo proxy. It will forward incoming connections.

  //	****		proxy.js		****

var net = require('net')
// need to create a server ↴
net.createServer(function (stream) {
  // on every connection we need to connect to the other side
  // we could emit `localhost` below ↴
  // then you can pipe back ↴