Search code examples
phpzeromqreactphp

React/ZMQ: REQ REP only working once


I'm trying to get a request to my server via a websocket, and return a reply from the server. This is "sort of" working, however I can only do this once, any extra requests just hang somewhere.

Server Bind:

$pull = $context->getSocket(ZMQ::SOCKET_REP);
$pull->bind('tcp://127.0.0.1:5552');
$pull->on('message', array($pusher, 'onPull'));
$pull->recv();
$pull->send('back');

I have a static PHP file on my server, which when I run, want to return the reply from the server:

$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'Sock');
$socket->connect("tcp://localhost:5552");

$socket->send('sending');

$message = $socket->recv();

echo "$message";

Now when I boot the server and run my php file, I get the "back" response back. However when I try to run it again it just hangs. I'm receiving the request each time?

Also, can anyone explain the $pull->on bit to me, I cannot find anywhere what it does.


Full server code:

<?php
    require './vendor/autoload.php';

    $loop   = React\EventLoop\Factory::create();
    $pusher = new MyApp\Pusher;

    $context = new React\ZMQ\Context($loop);

    $push = $context->getSocket(ZMQ::SOCKET_PULL);
    $push->bind('tcp://127.0.0.1:5555');
    $push->on('message', array($pusher, 'onNewPush'));

    $pull = $context->getSocket(ZMQ::SOCKET_REP);
    $pull->bind('tcp://127.0.0.1:5552');
    $pull->on('message', array($pusher, 'onPull'));
    $pull->recv();
    $pull->send('back');

    $webSock = new React\Socket\Server($loop);
    $webSock->listen(8080, '0.0.0.0');
    $webServer = new Ratchet\Server\IoServer(
        new Ratchet\Http\HttpServer(
            new Ratchet\WebSocket\WsServer(
                $pusher
            )
        ),
        $webSock
    );

    $loop->run();

Solution

  • I think something like this should do the job:

    $pull->on(
        'message',
        function ($message) use ($pull) {
            $pull->send('response');
        }
    );
    

    In any case, whether you use an anonymous function like above or an object/method pair, you need access to $pull, because that is the communication channel that allows you to send messages. The example at http://socketo.me/docs/push, which seems to be the base of your code, doesn't need that, since it uses a pull socket, which only receives messages.