Node.js WebSocket server

How to set up a simple Node.js WebSocket server on your laptop or embedded device and access it securely, to provide a real time UI.

This app note works for BeagleBone, Mac OS X, Raspberry Pi and other Linux devices running Node.js. Found a bug? Let us know.

Installing the ws Node.js WebSocket library

  1. Open a shell on your device, or type
    $ cd ~
  2. Create a nodejs-websocket-server directory
    $ mkdir nodejs-websocket-server
    $ cd nodejs-websocket-server
  3. Download and save the ws library with
    $ npm install --save ws

Setting up remote Web access to your device

  1. Install YalerTunnel and enable Web access via Yaler
    Install YalerTunnel on BeagleBone, Mac OS X, Raspberry Pi or another device
  2. Make sure to set the local port to 8080, enable TLS and use your relay domain
    $ ./yalertunnel server 127.0.0.1:8080 ssl:try.yaler.io:443 RELAY_DOMAIN
  3. Done. Now set up the echo server or the stat server example.


Echo server

A simple WebSocket server returning the message it receives.

Creating a Node.js WebSocket server

  1. Create a file named echo-server.js, e.g. with
    $ cd ~/nodejs-websocket-server
    $ sudo nano echo-server.js
    Enter the following Node.js code
    var WebSocketServer = require('ws').Server
      , wss = new WebSocketServer({ port: 8080 });
    
    wss.on('connection', function connection(ws) {
      ws.on('message', function incoming(message) {
        console.log(message);
        ws.send(message);
      });
    });

    Save changes with CTRL-X, then Y, then RETURN.

  2. Start the Node.js WebSocket server with
    $ node echo-server.js

Using the WebSocket.org echo client

  1. Open the WebSocket.org echo client https://www.websocket.org/echo.html
  2. Set location to wss://RELAY_DOMAIN.try.yaler.io/ and check Use secure WebSocket.
  3. Click Connect, type a message and click Send to send a WebSocket request.
  4. Done. You should now see the echo of your message.


Stat server

A combined Web/WebSocket server pushing server statistics, as found in ws examples.

Creating a combined Web/Websocket server

  1. Download and save the express package
    $ cd ~/nodejs-websocket-server
    $ npm install --save express
  2. Create a file named stat-server.js, e.g. with
    $ sudo nano stat-server.js
    Enter and save the following Node.js code
    // (c) 2011 Einar Otto Stangvik, MIT License
    var WebSocketServer = require('ws').Server
      , http = require('http')
      , express = require('express')
      , app = express();
    
    app.use(express.static(__dirname + '/public'));
    
    var server = http.createServer(app);
    server.listen(8080);
    
    var wss = new WebSocketServer({server: server});
    wss.on('connection', function(ws) {
      var id = setInterval(function() {
        ws.send(JSON.stringify(process.memoryUsage()), 
          function() { /* ignore errors */ });
      }, 100);
      ws.on('close', function() {
        clearInterval(id);
      });
    });

Creating a simple WebSocket client Web page

  1. Create a subdirectory public with a file named index.html, e.g. with
    $ mkdir public
    $ sudo nano public/index.html
    Enter and save the following HTML
    <!DOCTYPE html><!-- (c) 2011 Einar Otto Stangvik, MIT License -->
    <html>
      <head>
        <script>
          function updateStats(memuse) {
            document.getElementById('rss').innerHTML = memuse.rss;
            document.getElementById('heapTotal').innerHTML = memuse.heapTotal;
            document.getElementById('heapUsed').innerHTML = memuse.heapUsed;
          }
          var host = window.document.location.host.replace(/:.*/, '');
          var ws = new WebSocket('wss://' + host + '/');
          ws.onmessage = function (event) {
            updateStats(JSON.parse(event.data));
          };
        </script>
      </head>
      <body>
        RSS: <div id='rss'></div><br>
        Heap total: <div id='heapTotal'></div><br>
        Heap used: <div id='heapUsed'></div><br>
      </body>
    </html>

Accessing the combined Web/WebSocket server remotely

  1. Start the Node.js Web/WebSocket server with
    $ node stat-server.js
  2. To access the Web/WebSocket server, visit the URL
    https://RELAY_DOMAIN.try.yaler.io/ 
    e.g. for the relay domain gsiot-ffmq-ttd5 go to
    https://gsiot-ffmq-ttd5.try.yaler.io/
  3. Done. You should now see a real time stats Web page served by your device.


Troubleshooting

How to fix common issues.


Need more relay domains to serve Web and WebSocket requests on separate ports? Get in touch.


Creative Commons License This work by Yaler GmbH is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.