/examples/PHP/rtdealer.php

https://github.com/zetaben/zguide · PHP · 77 lines · 52 code · 13 blank · 12 comment · 12 complexity · acb98637cb90fbc7ee13bc022ecb07ee MD5 · raw file

  1. <?php
  2. /*
  3. * Custom routing Router to Dealer (XREP to XREQ)
  4. * @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
  5. */
  6. // We have two workers, here we copy the code, normally these would
  7. // run on different boxes...
  8. function worker_a() {
  9. $context = new ZMQContext();
  10. $worker = $context->getSocket(ZMQ::SOCKET_XREQ);
  11. $worker->setSockOpt(ZMQ::SOCKOPT_IDENTITY, "A");
  12. $worker->connect("ipc://routing.ipc");
  13. $total = 0;
  14. while(true) {
  15. // We receive one part, with the workload
  16. $request = $worker->recv();
  17. if($request == 'END') {
  18. printf ("A received: %d%s", $total, PHP_EOL);
  19. break;
  20. }
  21. $total++;
  22. }
  23. }
  24. function worker_b() {
  25. $context = new ZMQContext();
  26. $worker = $context->getSocket(ZMQ::SOCKET_XREQ);
  27. $worker->setSockOpt(ZMQ::SOCKOPT_IDENTITY, "B");
  28. $worker->connect("ipc://routing.ipc");
  29. $total = 0;
  30. while(true) {
  31. // We receive one part, with the workload
  32. $request = $worker->recv();
  33. if($request == 'END') {
  34. printf ("B received: %d%s", $total, PHP_EOL);
  35. break;
  36. }
  37. $total++;
  38. }
  39. }
  40. $pid = pcntl_fork();
  41. if($pid == 0) { worker_a(); exit(); }
  42. $pid = pcntl_fork();
  43. if($pid == 0) { worker_b(); exit(); }
  44. $context = new ZMQContext();
  45. $client = new ZMQSocket($context, ZMQ::SOCKET_XREP);
  46. $client->bind("ipc://routing.ipc");
  47. // Wait for threads to stabilize
  48. sleep(1);
  49. // Send 10 tasks scattered to A twice as often as B
  50. for ($task_nbr = 0; $task_nbr != 10; $task_nbr++) {
  51. // Send two message parts, first the address...
  52. if(mt_rand(0, 2) > 0) {
  53. $client->send("A", ZMQ::MODE_SNDMORE);
  54. } else {
  55. $client->send("B", ZMQ::MODE_SNDMORE);
  56. }
  57. // And then the workload
  58. $client->send("This is the workload");
  59. }
  60. $client->send("A", ZMQ::MODE_SNDMORE);
  61. $client->send("END");
  62. $client->send("B", ZMQ::MODE_SNDMORE);
  63. $client->send("END");
  64. sleep (1); // Give 0MQ/2.0.x time to flush output