Skip to content

Instantly share code, notes, and snippets.

@lancecarlson
Created January 19, 2016 15:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancecarlson/fb0cfd0354005098d579 to your computer and use it in GitHub Desktop.
Save lancecarlson/fb0cfd0354005098d579 to your computer and use it in GitHub Desktop.
ZeroMQ HTTP example
clang -Wall http.c -o http -L/usr/local/Cellar/zeromq/4.0.5_2/lib/ -lzmq && ./http
#include <zmq.h>
#include <string.h>
#include <assert.h>
int main (void) {
void *ctx = zmq_ctx_new ();
assert (ctx);
/* Create ZMQ_STREAM socket */
void *socket = zmq_socket (ctx, ZMQ_STREAM);
assert (socket);
int rc = zmq_bind (socket, "tcp://*:8080");
assert (rc == 0);
/* Data structure to hold the ZMQ_STREAM ID */
uint8_t id [256];
size_t id_size = 256;
while (1) {
/* Get HTTP request; ID frame and then request */
id_size = zmq_recv (socket, id, 256, 0);
assert (id_size > 0);
/* Prepares the response */
char http_response [] =
"HTTP/1.0 200 OK\r\n"
"Content-Type: text/plain\r\n"
"\r\n"
"Hello, World!";
/* Sends the ID frame followed by the response */
zmq_send (socket, id, id_size, ZMQ_SNDMORE);
zmq_send (socket, http_response, strlen (http_response), ZMQ_SNDMORE);
/* Closes the connection by sending the ID frame followed by a zero response */
zmq_send (socket, id, id_size, ZMQ_SNDMORE);
zmq_send (socket, 0, 0, ZMQ_SNDMORE);
/* NOTE: If we don't use ZMQ_SNDMORE, then we won't be able to send more */
/* message to any client */
}
zmq_close (socket); zmq_ctx_destroy (ctx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment