Permalink
Browse files

Merge pull request #181 from rgagnon24/master

New examples for PHP
  • Loading branch information...
2 parents eae145f + 70f8de0 commit db27aacc7d8dd2f97b26110f6272f0254696ae29 @hintjens hintjens committed Feb 27, 2012
Showing with 103 additions and 0 deletions.
  1. +1 −0 CONTRIBUTORS
  2. +79 −0 examples/PHP/flclient1.php
  3. +23 −0 examples/PHP/flserver1.php
View
@@ -78,6 +78,7 @@ Senthil Palanisami <spenthil@gmail.com> (Python)
John Gallagher (C, Python)
Tomas Roos (C#)
Stephen McQuay <stephen@mcquay.me> (C++)
+Rob Gagnon <rgagnon24@gmail.com> (PHP)
Errata and Suggestions
----------------------
@@ -0,0 +1,79 @@
+<?php
+/*
+* Freelance Client - Model 1
+* Uses REQ socket to query one or more services
+*
+* Author: Rob Gagnon <rgagnon24(at)gmail(dot)com>
+*/
+
+$request_timeout = 1000; // ms
+$max_retries = 3; # Before we abandon
+
+/**
+* @param ZMQContext $ctx
+* @param string $endpoint
+* @param string $request
+*/
+function try_request($ctx, $endpoint, $request) {
+ global $request_timeout;
+
+ printf("I: Trying echo service at %s...\n", $endpoint);
+ $client = $ctx->getSocket(ZMQ::SOCKET_REQ);
+ $client->connect($endpoint);
+ $client->send($request);
+
+ $poll = new ZMQPoll();
+ $poll->add($client, ZMQ::POLL_IN);
+ $readable = $writable = array();
+
+ $events = $poll->poll($readable, $writable, $request_timeout);
+ $reply = null;
+ foreach($readable as $sock) {
+ if ($sock == $client) {
+ $reply = $client->recvMulti();
+ } else {
+ $reply = null;
+ }
+ }
+
+ $poll->remove($client);
+ $poll = null;
+ $client = null;
+ return $reply;
+}
+
+$context = new ZMQContext();
+$request = 'Hello world';
+$reply = null;
+
+$cmd = array_shift($argv);
+$endpoints = count($argv);
+if ($endpoints == 0) {
+ printf("I: syntax: %s <endpoint> ...\n", $cmd);
+ exit;
+}
+
+if ($endpoints == 1) {
+ // For one endpoint, we retry N times
+ $endpoint = $argv[0];
+ for($retries = 0; $retries < $max_retries; $retries++) {
+ $reply = try_request($context, $endpoint, $request);
+ if (isset($reply)) {
+ break; // Success
+ }
+ printf("W: No response from %s, retrying\n", $endpoint);
+ }
+} else {
+ // For multiple endpoints, try each at most once
+ foreach($argv as $endpoint) {
+ $reply = try_request($context, $endpoint, $request);
+ if (isset($reply)) {
+ break; // Success
+ }
+ printf("W: No response from %s\n", $endpoint);
+ }
+}
+
+if (isset($reply)) {
+ print "Service is running OK\n";
+}
@@ -0,0 +1,23 @@
+<?php
+/*
+* Freelance server - Model 1
+* Trivial echo service
+*
+* Author: Rob Gagnon <rgagnon24(at)gmail(dot)com>
+*/
+
+if (count($argv) < 2) {
+ printf("I: Syntax: %s <endpoint>\n", $argv[0]);
+ exit;
+}
+
+$endpoint = $argv[1];
+$context = new ZMQContext();
+$server = $context->getSocket(ZMQ::SOCKET_REP);
+$server->bind($endpoint);
+
+printf("I: Echo service is ready at %s\n", $endpoint);
+while(true) {
+ $msg = $server->recvMulti();
+ $server->sendMulti($msg);
+}

0 comments on commit db27aac

Please sign in to comment.