Skip to content

Instantly share code, notes, and snippets.

@timwhitlock
Last active November 7, 2019 15:09
Show Gist options
  • Save timwhitlock/c9cc8492c0b1a04171f8b754d869d079 to your computer and use it in GitHub Desktop.
Save timwhitlock/c9cc8492c0b1a04171f8b754d869d079 to your computer and use it in GitHub Desktop.
Simple 0MQ client/server pattern
<?php
// Client: Pings server, gets reply. Exits.
$zmq = new ZMQContext;
$sock = new ZMQSocket( $zmq, ZMQ::SOCKET_REQ );
$sock->connect('tcp://localhost:5555');
echo "Pinging..\n";
$sock->send('Ping');
echo "Client waiting..\n";
$pong = $sock->recv();
echo $pong," in reply. exiting.\n";
<?php
// Server: Waits for ping, sends reply. Repeats.
$zmq = new ZMQContext;
$sock = new ZMQSocket( $zmq, ZMQ::SOCKET_REP );
$sock->bind('tcp://*:5555');
while( true ){
echo "Server waiting..\n";
$ping = $sock->recv();
echo "Acknowledging ",$ping,"..\n";
$sock->send('Pong');
}
@timwhitlock
Copy link
Author

Run server.php in one terminal window.
Open a second terminal and run client.php

The client sends a ping, receives a reply and then exits. This is all done synchronously so each end of the socket hangs on the recv call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment