Friday, January 3, 2014

websocketd and Python for system monitoring - the JavaScript WebSocket client

By Vasudev Ram

In my previous post:

Use WebSockets and Python for web-based system monitoring ,

I said I'd show the HTML + JavaScript client code for the monitoring app in my next post. Here it is, in the file psutil_disk_usage.html:

<!DOCTYPE html>
<html>
    <head>
        <title>
        Disk space monitoring with websocketd (Go) and psutil (Python).
        </title>
    </head>
    <body>
        <h3>
        Disk space monitoring with websocketd (Go) and psutil (Python).
        </h3>
        <p>
            <div id="log"></div>
        </p>
        <script>
            // helper function: log message to screen
            function log(msg) {
                document.getElementById('log').innerText += msg + '\n';
            }

            // setup websocket with callbacks
            var ws = new WebSocket('ws://localhost:8080/');
            ws.onopen = function() {
                log('CONNECT');
            };
            ws.onclose = function() {
                log('DISCONNECT');
            };
            ws.onmessage = function(event) {
                log('MESSAGE: ' + event.data);
            };
        </script>
    </body>
</html>
As you can see, the code is pretty straightforward. You open the above HTML file in a WebSocket-enabled browser after running the websocketd command I showed in my previous post. (If you start the HTML page before the websocketd command, the client socket times out and disconnects, because it has nothing to read.

Here is the output of running the websocketd command at the command line:


And here is the WebSocket client running in the browser, showing the first two lines of disk space info pushed to it by the server:


Though it was coincidental, I realized that the websocket-based system monitoring technique shown (in this post and my previous post) may be useful for collecting system or sensor data from devices in the Internet of Things (IoT), as I mentioned in this other recent post:

PTC Acquires ThingWorx, Internet of Things Platform Provider

, in which I said:

[ One point of interest is the use of the IoT for system monitoring. Since many more devices will have some intelligence (i.e. a processor built-in) and network access, monitoring systems comprising of many such "things" could be potentially easier and more scalable. ]

For example, many IoT devices could send their data (on weather, traffic, etc.) to a server, which could use WebSockets as in this example to push the analysed / consolidated / summarized data to a WebSocket client running in a browser, for human consumption.

- Vasudev Ram - Dancing Bison Enterprises

Contact Page



No comments: