amuck-landowner

Install and run zeromq

peterw

New Member
ØMQ \zeromq\:


 Ø  Connect your code in any language, on any platform.


 Ø  Carries messages across inproc, IPC, TCP, TPIC, multicast.


 Ø  Smart patterns like pub-sub, push-pull, and router-dealer.


 Ø  High-speed asynchronous I/O engines, in a tiny library.


 Ø  Backed by a large and active open source community.


 Ø  Supports every modern language and platform.


 Ø  Build any architecture: centralized, distributed, small, or large.


 Ø  Free software with full commercial support.
1. Installation:

2. Create server: "nano ~/server.php"


<?php
/*
* Weather update server
* Binds PUB socket to tcp://*:5556
* Publishes random weather updates
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/

// Prepare our context and publisher
$context = new ZMQContext();
$publisher = $context->getSocket(ZMQ::SOCKET_PUB);
$publisher->bind("tcp://*:5556");
$publisher->bind("ipc://weather.ipc");

while (true) {
// Get values that will fool the boss
$zipcode = mt_rand(0, 100000);
$temperature = mt_rand(-80, 135);
$relhumidity = mt_rand(10, 60);

// Send message to all subscribers
$update = sprintf ("%05d %d %d", $zipcode, $temperature, $relhumidity);
$publisher->send($update);
}


3. Create client: "nano ~/client.php"


<?php
/*
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and finds avg temp in zipcode
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/

$context = new ZMQContext();

// Socket to talk to server
echo "Collecting updates from weather server…", PHP_EOL;
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5556");

// Subscribe to zipcode, default is NYC, 10001
$filter = $_SERVER['argc'] > 1 ? $_SERVER['argv'][1] : "10001";
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, $filter);

// Process 100 updates
$total_temp = 0;
for ($update_nbr = 0; $update_nbr < 100; $update_nbr++) {
$string = $subscriber->recv();
sscanf ($string, "%d %d %d", $zipcode, $temperature, $relhumidity);
$total_temp += $temperature;
}
printf ("Average temperature for zipcode '%s' was %dF\n",
$filter, (int) ($total_temp / $update_nbr));


4. Install php extension: "apt-get install php-pear php5-dev && pecl install zmq-beta"

Add "extension=zmq.so" to your php.ini.

Run both with php server.php and php client.php.

Output of client is:

Code:
>php client.php
Collecting updates from weather server…
Average temperature for zipcode '10001' was 23F
 
Top
amuck-landowner