Friday, March 9, 2007

Adding a web interface to a C++ application

One thing that is always sort of a pain is setting up a graphical user interface. This is especially true if you are making an embedded application or something that functions more as a system service or daemon. In this case you probably end up creating some simple network protocol which you use to control your application via some other remote piece of software or just telnet if you are feeling especially lazy.

What would be nice, however, is to have a web based interface but not have to jump through a bunch of hoops to add it into your code. This sort of simple add-in HTTP server is exactly what this post is all about.

A few months ago I was spending Christmas with the family. Good times all around but they live out in the middle of nowhere. And when I mean nowhere I'm talking no TV, 1 bar on the cell phone during a 'clear' conversation, no internet, and some farm animals. We do have what is seemingly an ex-circus goat that walks around by balancing on just its front two feet. You can imagine how entertaining that is but even so it only occupies you for so long. So naturally I broke out my laptop and created just the thing I have always wanted, a simple HTTP server I can stick into my C++ applications. I love Christmas :)

The code for the thing is available from sourceforge. There is also a more involved example program that can be viewed in its entirety here, but for the sake of creating a somewhat tidy little tutorial I'll show a simple example.
#include <dlib/server.h>
using namespace dlib;

class web_server : public server_http
    const std::string on_request (
        const incoming_things& incoming,
        outgoing_things& outgoing    
        return "<html><body>Hurray for simple things!</body></html>";

int main()
    web_server our_web_server;
Basically what is happening here, if it isn't already obvious, is we are defining a class which acts as our HTTP server. To do this all you need to do is inherit from server_http and implement the virtual function on_request(). To turn it on just set the listening port number and call start(). That's it. If you compiled this and ran it you could check out the page it creates by directing your browser to http://localhost/ and it would pop up. You would see a page with the single line of text "Hurray for simple things!".

For an explanation of the arguments to the on_request() function check out the example program linked to above and/or check out the documentation on the dlib web site.