Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- #include 'zhelpers.php';
- if($argc<3||$argv[1]<1025||$argv[2]<2) {
- printf("Usage: %s <port> <n>\tPort greater than 1024 and at least 2 instances\n",$argv[0]);
- exit;
- }
- // Create a bunch of peers
- $peers = array();
- for($i=$argv[1];$i<$argv[1]+$argv[2];$i++) {
- $peers[]=array(
- "identity" => sprintf("NODE%d",$i),
- "uri" => sprintf("tcp://127.0.0.1:%d",$i));
- }
- // Let's make some kids
- foreach($peers as $id => $peer) {
- $pid = pcntl_fork();
- if($pid == -1)
- printf("Could not fork: %d\n",$id);
- else if ($pid) {
- sleep(1); // Pause a bit before forking the next peer
- } else {
- $me=$peer;
- cli_set_process_title($peer["uri"]);
- break;
- }
- }
- // The parent can die now, all the kids are alive
- if($pid) { exit; }
- // Get the kids started in a conversation...
- $ctx = new ZMQContext();
- $srv = $ctx->getsocket(ZMQ::SOCKET_ROUTER);
- $srv->SetSockOpt(ZMQ::SOCKOPT_IDENTITY,$me["identity"]);
- foreach($peers as $id=>$peer) {
- if($peer == $me) {
- printf("%s binding: %s\n",$me["identity"],$me["uri"]);
- $srv->bind($me["uri"]);
- unset($peers[$id]);
- break; // Do not connect to subsequent peers, they'll connect to us
- } else {
- printf("%s connect: %s\n",$me["identity"], $peer["uri"]);
- $srv->connect($peer["uri"]);
- }
- }
- // Wait for all the kids to settle down
- // For fun, check out what happens without a short nap
- sleep(2+count($peers));
- // We're only going to send 4 messages, but we need to loop for about
- // 10 seconds to be sure that we receive all of them.
- // We'll use these counters for the loop and to count all the messages
- $loop=$msgr=$msgs=0;
- for($i=0;$i<10;$i++) {
- if($loop++<4) {
- echo PHP_EOL;
- foreach($peers as $peer) {
- $hello = sprintf("%s>%s (%02d)",$me["identity"],$peer["identity"],$msgs);
- echo $hello . PHP_EOL;
- $hello = array($peer["identity"],'',$hello);
- if($srv->sendmulti($hello)) $msgs++;
- }
- }
- sleep(1);
- while($message = $srv->recvMulti(ZMQ::MODE_DONTWAIT)) {
- $msgr++;
- }
- }
- echo PHP_EOL;
- printf("%s: Total Recv: %d\n",$me["identity"],$msgr);
- printf("%s: Total Sent: %d\n",$me["identity"],$msgs);
Advertisement
Add Comment
Please, Sign In to add comment