Showing posts with label websocketd. Show all posts
Showing posts with label websocketd. Show all posts

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



Use WebSockets and Python for web-based system monitoring

By Vasudev Ram

I got to know about websocketd recently, via a reply to this question I posted on Hacker News: Ask HN: What are you using Go for?

websocketd is "a small command-line tool that will wrap an existing command-line interface program, and allow it to be accessed via a WebSocket". It's written in Go, by Joe Walnes.

He describes websocketd as "Like inetd, but for WebSockets. Turn any application that uses STDIN/STDOUT into a WebSocket server.".

The websocketd README goes on to say:

[ WebSocket-capable applications can now be built very easily. As long as you can write an executable program that reads STDIN and writes to STDOUT, you can build a WebSocket server. Do it in Python, Ruby, Perl, Bash, .NET, C, Go, PHP, Java, Clojure, Scala, Groovy, Expect, Awk, VBScript, Haskell, Lua, R, whatever! No networking libraries necessary. ]

Websocket topic on Wikipedia

So I wrote a small Python program to try out websocketd. It uses the psutil module to get disk space info (total, used, and free) from the system.

(I had blogged about psutil earlier, here:

psutil, Python tool to get process info and more.)

Here is the code:
# psutil_disk_usage.py

import string
from time import sleep
import psutil

print "Disk Space (MB)".rjust(46)
print " ".rjust(25) + "Total".rjust(10) + "Used".rjust(10) + "Free".rjust(10)  
for i in range(5):
    du = psutil.disk_usage('/')
    print str(i + 1).rjust(25) + str(du.total/1024/1024).rjust(10) + str(du.used/1024/1024).rjust(10) + str(du.free/1024/1024).rjust(10)  
    sleep(2)

When this program is run directly at the prompt, with the command:

python psutil_disk_usage.py

, it gives this output:
Disk Space (MB)
                             Total      Used      Free
                       1     99899     91309      8590
                       2     99899     91309      8590
                       3     99899     91309      8590
                       4     99899     91309      8590
                       5     99899     91309      8590
Running this program under the control of websocketd, with the command:

websocketd --port=8080 python psutil_disk_usage.py

, causes the output of the program to go to the browser that is listening on port 8080 (see below *).

You have to:

set PYTHONUNBUFFERED=true

at the command line first, for it to work as a WebSocket server; it works fine as a plain command-line program, without that setting.

See this StackOverflow question.

(*) You also have to write a WebSocket client, i.e. an HTML page with JavaScript, that the server can connect to, and send data to. The JavaScript code listens for a connection and then reads the data sent by the server and displays it on the web page.

In my next post, I'll show the JavaScript WebSocket client, which is a modified version of an example on the websocketd page.

- Vasudev Ram - Dancing Bison Enterprises

Contact Page

Vitamins & Supplements