Websocket Node Client

In notebook:
FrontEndMasters Networking and Streams
Created at:
2017-09-30
Updated:
2017-09-30
Tags:
backend Node JS JavaScript

Demoes that the previous live coded example works.


websocket-stream: server

var http = require('http')
var wsock = require('websocket-stream')
var through = require('through2')

var server = http.createServer(function (req, res) {
  res.end('not found\n')
}).listen(5000)
wsock.createServer({ server: server }, function (stream) {
  stream.pipe(louder()).pipe(stream)
})

function louder () {
  return through(function (buf, enc, next) {
    next(null, buf.toString().toUpperCase())
  })
}

websocket-stream: node client

To use websockets in NodeJS instead of the browser:

var wsock = require('websocket-stream')
var stream = wsock('ws://localhost:5000')
process.stdin.pipe(stream).pipe(process.stdout)

websocket-stream: browser client

var wsock = require('websocket-stream')
var to = require('to2')
var html = require('yo-yo')
var root = document.body.appendChild(document.createElement('div'))
var output = []
update()

var stream = wsock('ws://localhost:5000')
stream.pipe(to(function (buf, enc, next) {
  output.push(buf.toString())
  update()
  next()
}))

function update () {
  html.update(root, html`<div>
    <form onsubmit=${onsubmit}>
      <input name="msg" type="text">
    </form>
    <pre>${output.join('')}</pre>
  </div>`)
  function onsubmit (ev) {
    ev.preventDefault()
    stream.write(this.elements.msg.value + '\n')
    this.reset()
  }
}