Guest User

Untitled

a guest
Jun 21st, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1.  
  2. Publisher ----------
  3.  
  4. #include "zhelpers.h"
  5.  
  6. int main () {
  7. // Prepare our context and publisher
  8. void *context = zmq_init (1);
  9. void *publisher = zmq_socket (context, ZMQ_PUB);
  10. zmq_bind (publisher, "tcp://*:5556");
  11. zmq_bind (publisher, "ipc://weather.ipc");
  12.  
  13. // Initialize random number generator
  14. srandom ((unsigned) time (NULL));
  15. while (1) {
  16. // Get values that will fool the boss
  17. int zipcode, temperature, relhumidity;
  18. zipcode = within (100000);
  19. temperature = within (215) - 80;
  20. relhumidity = within (50) + 10;
  21.  
  22. // Send message to all subscribers
  23. char update [20];
  24. sprintf (update, "%05d %d %d", zipcode, temperature, relhumidity);
  25. s_send (publisher, update);
  26. }
  27. zmq_close (publisher);
  28. zmq_term (context);
  29. return 0;
  30. }
  31.  
  32.  
  33.  
  34.  
  35. Subscriber --------------
  36.  
  37. #include "zhelpers.h"
  38.  
  39. int main (int argc, char *argv[])
  40. {
  41. void *context = zmq_init (1);
  42.  
  43. // Socket to talk to server
  44. printf ("Collecting updates from weather server...\n");
  45. void *subscriber = zmq_socket (context, ZMQ_SUB);
  46. zmq_connect (subscriber, "tcp://localhost:5556");
  47.  
  48. // Subscribe to zipcode, default is NYC, 10001
  49. char *filter = (argc > 1)? argv [1]: "10001 ";
  50. zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE, filter, strlen (filter));
  51. while(1)
  52. {
  53. // Process 100 updates
  54. int update_nbr;
  55. long total_temp = 0;
  56. for (update_nbr = 0; update_nbr < 100; update_nbr++) {
  57. char *string = s_recv (subscriber);
  58. int zipcode, temperature, relhumidity;
  59. sscanf (string, "%d %d %d",
  60. &zipcode, &temperature, &relhumidity);
  61. total_temp += temperature;
  62. free (string);
  63. }
  64. printf ("Average temperature for zipcode '%s' was %dF\n",
  65. filter, (int) (total_temp / update_nbr));
  66. }
  67. zmq_close (subscriber);
  68. zmq_term (context);
  69. return 0;
  70. }
Add Comment
Please, Sign In to add comment