Guest User

0MQ Router Example

a guest
Mar 9th, 2014
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.17 KB | None | 0 0
  1. <?php
  2.  
  3. #include 'zhelpers.php';
  4.  
  5. if($argc<3||$argv[1]<1025||$argv[2]<2) {
  6.   printf("Usage: %s <port> <n>\tPort greater than 1024 and at least 2 instances\n",$argv[0]);
  7.   exit;
  8. }
  9.  
  10. // Create a bunch of peers
  11.  
  12. $peers = array();
  13. for($i=$argv[1];$i<$argv[1]+$argv[2];$i++) {
  14.   $peers[]=array(
  15.     "identity" => sprintf("NODE%d",$i),
  16.     "uri" => sprintf("tcp://127.0.0.1:%d",$i));
  17. }
  18.  
  19.  
  20. // Let's make some kids
  21.  
  22. foreach($peers as $id => $peer) {
  23.   $pid = pcntl_fork();
  24.   if($pid == -1)
  25.     printf("Could not fork: %d\n",$id);
  26.   else if ($pid) {
  27.     sleep(1); // Pause a bit before forking the next peer
  28.   } else {
  29.     $me=$peer;
  30.     cli_set_process_title($peer["uri"]);
  31.     break;
  32.   }
  33. }
  34.  
  35. // The parent can die now, all the kids are alive
  36.  
  37. if($pid) { exit; }
  38.  
  39. // Get the kids started in a conversation...
  40.  
  41. $ctx = new ZMQContext();
  42. $srv = $ctx->getsocket(ZMQ::SOCKET_ROUTER);
  43. $srv->SetSockOpt(ZMQ::SOCKOPT_IDENTITY,$me["identity"]);
  44.  
  45. foreach($peers as $id=>$peer) {
  46.   if($peer == $me) {
  47.     printf("%s binding: %s\n",$me["identity"],$me["uri"]);
  48.     $srv->bind($me["uri"]);
  49.     unset($peers[$id]);
  50.     break; // Do not connect to subsequent peers, they'll connect to us
  51.   } else {
  52.     printf("%s connect: %s\n",$me["identity"], $peer["uri"]);
  53.     $srv->connect($peer["uri"]);
  54.   }
  55. }
  56.  
  57. // Wait for all the kids to settle down
  58. // For fun, check out what happens without a short nap
  59.  
  60. sleep(2+count($peers));
  61.  
  62.  
  63. // We're only going to send 4 messages, but we need to loop for about
  64. // 10 seconds to be sure that we receive all of them.
  65.  
  66. // We'll use these counters for the loop and to count all the messages
  67.  
  68. $loop=$msgr=$msgs=0;
  69.  
  70. for($i=0;$i<10;$i++) {
  71.   if($loop++<4) {
  72.     echo PHP_EOL;
  73.     foreach($peers as $peer) {
  74.       $hello = sprintf("%s>%s (%02d)",$me["identity"],$peer["identity"],$msgs);
  75.       echo $hello . PHP_EOL;
  76.       $hello = array($peer["identity"],'',$hello);
  77.       if($srv->sendmulti($hello)) $msgs++;
  78.     }
  79.   }
  80.  
  81.   sleep(1);
  82.  
  83.   while($message = $srv->recvMulti(ZMQ::MODE_DONTWAIT)) {
  84.     $msgr++;
  85.   }
  86. }
  87.  
  88. echo PHP_EOL;
  89.  
  90. printf("%s: Total Recv: %d\n",$me["identity"],$msgr);
  91. printf("%s: Total Sent: %d\n",$me["identity"],$msgs);
Advertisement
Add Comment
Please, Sign In to add comment