Raspberry Pi Websocket Demo NGINX + NODE.JS

Das folgende Beispiel soll auf dem Raspberry Pi eine Websocket Kommunikation unter Verwendung von NGINX als Webserver + Websocket-Proxy und NODEJS als Websocket-Server demonstrieren:

Vorbereitungen:

  1. Installation von NGINX
  2. Installation von NODEJS
  3. sudo usermod -aG www-data pi

Websocketserver (NODEJS) starten:

console.log("Websocket-Server started");
var Msg = '';
var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port: 8010});
    wss.on('connection', function(ws) {
        ws.on('message', function(message) {
        console.log('Received from client: %s', message);
        //ws.send('Server received from client: ' + message);
                        
        const spawn = require('child_process').spawn;
        const myCmd = spawn('netstat', ['-ntp']);

        myCmd.stdout.on('data', (data) => {
        ws.send(`${data}`);
        });

        myCmd.stderr.on('data', (data) => {
        //ws.send(`stderr: ${data}`);
        });

        myCmd.on('close', (code) => {
        ws.send(`child process exited with code ${code}`);
        });

    });
 });

Den NODEJS Code als websocketserver.js abspeichern und in diesem Verzeichnis das nodejs Modul ws wie folgt installieren sowie das Programm auf dem Raspberry starten:

npm install --save ws
node websocketserver.js

Die beiden nachfolgenden Dateien myws.html und myws.js nach /var/www/html auf den Raspberry kopieren:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Raspberry Pi NODEJS NGINX Websocket example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style>
p.mono {
    font-family: monospace, Courier, "Courier New";
}
</style>
</head>

<body>
  <h2>Raspberry Pi NODEJS NGINX WEBPROXY Websocket example</h2>
  <h3>E.g. call <font color=green>netstat -ntp</font> on your Raspberry Pi</h3>
  <button id="btn1">Get websocket data</button>
  <button id="btn2">Clear</button>

  <p class="mono" id="output"></p>
  <p id="failure"></p>

<script>


$("#btn1").click(function(){
  createWebSocket();
});

$("#btn2").click(function(){
  $("#output").text("");
  $("#failure").text("");
});


</script>
<!-- load the websocket javascript file -->
<script src="myws.js"></script>
</body>
</html> 
/* websocket example myws.js */
var ip = location.hostname;
var port = location.port;
var wsUrl = 'ws://' + ip + '/socket';
var myws;

function createWebSocket()
{
  myws = new WebSocket(wsUrl);
  myws.onopen = function(evt) { onOpen(evt) };
  myws.onclose = function(evt) { onClose(evt) };
  myws.onmessage = function(evt) { onMessage(evt) };
  myws.onerror = function(evt) { onError(evt) };
}

function onOpen(evt)
{  
  $("#output").append("<font color=green>CONNECTED</font>");
  doSend("WebSocket runs well with NGINX proxy");
}

function onClose(evt)
{
  $("#output").append("<font color=red>DISCONNECTED</font><br>");
}

function onMessage(evt)
{
   var aData = evt.data.split("\n");      
   var k = 0;
   var len = aData.length;
  
  //console.log(evt.data);
 
  for (k=0; k < len; k++)
  {
    if (aData[k].length > 0)
      $("#output").append('<li>'+ aData[k] +'</li>');    
  }
  myws.close();
}

function onError(evt)
{
  $("#failure").append('<li>'+ evt.data +'</li>');
}

function doSend(message)
{
  myws.send(message);
}