Advertisement
gosta100

zmq_fileserver.c

Nov 18th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. #include <czmq.h>
  2. #define CHUNK_SIZE 4096
  3. #define PIPELINE 10
  4.  
  5. static void
  6. free_chunk (void *data, void *arg)
  7. {
  8.   free (data);
  9. }
  10.  
  11. int main (void)
  12. {
  13.   zctx_t *ctx = zctx_new ();
  14.  
  15.   FILE *file = fopen ("TestFiles/100K.bin", "r");
  16.   assert (file);
  17.  
  18.   void *router = zsocket_new (ctx, ZMQ_ROUTER);
  19.   zsocket_set_hwm (router, PIPELINE);
  20.   zsocket_bind (router, "tcp://*:6000");
  21.   while (true) {
  22.     // First frame in each message is the sender identity
  23.     zframe_t *identity = zframe_recv (router);
  24.     if (!identity)
  25.       break; // Shutting down, quit
  26.  
  27.     // Second frame is "fetch" command
  28.     char *command = zstr_recv (router);
  29.     assert (streq (command, "fetch"));
  30.     free (command);
  31.  
  32.     // Third frame is chunk offset in file
  33.     char *offset_str = zstr_recv (router);
  34.     size_t offset = atoi (offset_str);
  35.     free (offset_str);
  36.  
  37.     // Fourth frame is maximum chunk size
  38.     char *chunksz_str = zstr_recv (router);
  39.     size_t chunksz = atoi (chunksz_str);
  40.     free (chunksz_str);
  41.  
  42.     // Read chunk of data from file
  43.     fseek (file, offset, SEEK_SET);
  44.     byte *data = malloc (chunksz);
  45.     assert (data);
  46.  
  47.     // Send resulting chunk to client
  48.     size_t size = fread (data, 1, chunksz, file);
  49.     zframe_t *chunk = zframe_new_zero_copy (data, size, free_chunk, NULL);
  50.     zframe_send (&identity, router, ZFRAME_MORE);
  51.     zframe_send (&chunk, router, 0);
  52.   }
  53.   fclose (file);
  54.  
  55.   zctx_destroy (&ctx);
  56.   return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement