ZMQ - ZeroMQ as a http server

If you don't know ZMQ, you really should. take a look: http://zguide.zeromq.org/page:all 

And yes, it is all that!

You can use any language to use it.

But for me let's stay fast and use C.

You know, just download, build and install like any autotools compliant tool.

For message queue there are a plenty of samples in manual. Then I will not talk about it. But in our web world, we need something to listen HTTP then it allow us to elaborate something like a sync/assync gateway that convert synchronous http request in assynchronous distributed by MQ tasks.

This seems to be complex, but not in ZMQ.

I very busy these days, so just a bit of code for now:
 
// Minimal HTTP server in 0MQ
#include "zhelpers.h"

int main (void)
{
        int rc;

        // Set-up our context and sockets
        void *ctx = zmq_ctx_new ();
        assert (ctx);

        // Start our server listening
        void *server = zmq_socket (ctx, ZMQ_STREAM);
        zmq_bind (server, "tcp://*:8080");
        assert (server);
        uint8_t id[256];
        size_t id_size = 256;

        while (1)
        {
                // Get HTTP request;
                // first frame has ID, the next the request.
                id_size = zmq_recv (server, id, 256, 0);
                assert (id_size > 0);

                // Get HTTP request
                char *request = s_recv (server);
                puts (request); // Professional Logging(TM)
                free (request); // We throw this away

                // define the response
                char http_response [] =
                        "HTTP/1.0 200 OK\n"
                        "Content-Type: text/html\n"
                        "\n"
                        "Hello, World!\n";

                // start sending response
                rc = zmq_send (server, id, id_size, ZMQ_SNDMORE);
                assert (rc != -1);
                // Send the http response
                rc = zmq_send ( server, 
                         http_response,
                         sizeof (http_response),
                         ZMQ_SNDMORE
                        );
                assert (rc != -1);

                // Send a zero to close connection to client
                rc = zmq_send(server, id, id_size, ZMQ_SNDMORE);
                assert (rc != -1);
                rc = zmq_send(server, NULL, 0, ZMQ_SNDMORE);
                assert (rc != -1);
        }

        rc = zmq_close (server);
        assert (rc == 0);

        rc = zmq_ctx_term (ctx);
        assert (rc == 0);

        return 0;
}

save this block as httpserver.c and build it with
gcc -o httpserver httpserver.c -lzmq
run it and see open http://localhost:8080... just see the magic happening.

Oh... the "zhelpers.h" are in sources, but you can get it here to
#include 
#include 
#include 
#include 

Read the docs.
Postar um comentário

Postagens mais visitadas