foto Petr Bravenec

Petr Bravenec
Twitter: @BravenecPetr
+420 777 566 384

Few weeks ago I described simple http server for Qt a and universal API to access application data – today I will show you how to use HTML5 event stream.

You can find overview of http server here: Our work - Http Server for C++ and Qt

We use the server in a embedded applications built on BeagleBone Black. HTML pages in such device use usual structure:

  • HTML code served by application is Static – it is only a template and the actual data are shown later.
  • Every page contains its own JavaScript code. In cooperation with universal API the JavaScript code obtains data from application and includes it to page.
  • JavaScript code maintains persistent connection to application and all changes are immediately shown in web browser window – I will describe this part today.

See the live example. How it works?

HTML source shows only a simple table without any data (I ignored other parts of page):

<table id="tabledata">

The table is empty – data are obtained using JavaScript and HTML event stream:

    var source = new EventSource("/example/events");
    source.addEventListener("status", function(event) {
        var data = JSON.parse(event.data);
        var id = data.id;
        var rowdata = 
            "" + 
            "" + data.id + "" +
            "" + data.text + "" +
            "" + data.counter + "" +
            "detail" +
        var rowelement = $("table#tabledata tbody tr#"+id);
        if (rowelement.text() == "") {
            $("table#tabledata tbody").append( rowdata );
          } else {
            rowelement.replaceWith( rowdata );
        }, false);

First line is the construction of jQuery, the second one installs the event stream and on other lines the event is processed. Code will not work in MS Explorer, this web browser do not support HTML5 event streams. Other browser are usually without problems.

Please note the line installing event stream processing:

var source = new EventSource("/example/events");

String "/example/events" is a relative URL linking event stream. Please, see prior article to understand how the address is created in HobrasoftHttp server.

There is nothing magic about HTML5 event streams. Their use is simple and effective. A lot of detailed articles can be found on Internet:

Stream Updates with Server-Sent Events


I wanted to show interesting and simple technology in this article. My experience shows that embedded application developers – single chip micro-controllers, BeagleBone, Raspberry and other – very often has only small knowledge in web technologies. And the reverse is also true - web developers have the knowledge in hardware even smaller. But both worlds can be connected so easily.

Hobrasoft s.r.o. | Contact