当前位置: 首页>>代码示例>>PHP>>正文


PHP ZMQSocket类代码示例

本文整理汇总了PHP中ZMQSocket的典型用法代码示例。如果您正苦于以下问题:PHP ZMQSocket类的具体用法?PHP ZMQSocket怎么用?PHP ZMQSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ZMQSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: client_thread

function client_thread($self)
{
    $context = new ZMQContext();
    $client = new ZMQSocket($context, ZMQ::SOCKET_REQ);
    $endpoint = sprintf("ipc://%s-localfe.ipc", $self);
    $client->connect($endpoint);
    $monitor = new ZMQSocket($context, ZMQ::SOCKET_PUSH);
    $endpoint = sprintf("ipc://%s-monitor.ipc", $self);
    $monitor->connect($endpoint);
    $readable = $writeable = array();
    while (true) {
        sleep(mt_rand(0, 4));
        $burst = mt_rand(1, 14);
        while ($burst--) {
            //  Send request with random hex ID
            $task_id = sprintf("%04X", mt_rand(0, 10000));
            $client->send($task_id);
            //  Wait max ten seconds for a reply, then complain
            $poll = new ZMQPoll();
            $poll->add($client, ZMQ::POLL_IN);
            $events = $poll->poll($readable, $writeable, 10 * 1000000);
            if ($events > 0) {
                foreach ($readable as $socket) {
                    $zmsg = new Zmsg($socket);
                    $zmsg->recv();
                    //  Worker is supposed to answer us with our task id
                    assert($zmsg->body() == $task_id);
                }
            } else {
                $monitor->send(sprintf("E: CLIENT EXIT - lost task %s", $task_id));
                exit;
            }
        }
    }
}
开发者ID:nivertech,项目名称:zguide,代码行数:35,代码来源:peering3.php

示例2: receiveResponse

 /**
  * {@inheritDoc}
  */
 public function receiveResponse()
 {
     try {
         $result = $this->socket->recvMulti();
     } catch (\ZMQSocketException $e) {
         throw new TransportException('Cannot receive response', 0, $e);
     }
     if ($result === false) {
         throw new TimeoutException('Timeout (' . $this->getTimeout() . 's) reached');
     }
     if (!isset($result[0])) {
         throw new FormatException('Invalid response - no response type', $result);
     }
     if (!isset($result[1])) {
         throw new FormatException('Invalid response - no headers', $result);
     }
     $response = new Response($result[0]);
     $response->setHeaders(new Headers(Parser::parseHeaders($result[1])));
     if (!MessageTypes::isResponseTypeWithResult($response->getType())) {
         return $response;
     }
     if (!isset($result[2])) {
         throw new FormatException('Invalid response - no response body', $result);
     }
     return $response->setResultBody($result[2]);
 }
开发者ID:wookieb,项目名称:zorro-rpc,代码行数:29,代码来源:ZeroMQClientTransport.php

示例3: run

 public function run(OutputInterface $output)
 {
     $context = new \ZMQContext();
     $tasksQueue = new \ZMQSocket($context, \ZMQ::SOCKET_PULL);
     $tasksQueue->connect(Spider::ZMQ_TASKS_QUEUE_DSN);
     $resultsQueue = new \ZMQSocket($context, \ZMQ::SOCKET_PUSH);
     $resultsQueue->connect(Spider::ZMQ_RESULTS_QUEUE_DSN);
     $output->writeln('HTTP Worker is waiting for tasks');
     while (true) {
         $string = $tasksQueue->recv();
         if ($string === Spider::ZMQ_COMMAND_BATCH_START) {
             $resultsQueue->send($string);
         } elseif (stripos($string, Spider::ZMQ_COMMAND_BATCH_END) !== false) {
             // send info for result collector how many results it should expect
             $resultsQueue->send($string);
         } elseif ($string === Spider::ZMQ_COMMAND_WORKER_QUIT) {
             $output->writeln('No more work. Worker stops now.');
             break;
             // no more work
         } else {
             $output->writeln('Fetching data from URI: ' . $string);
             $userData = file_get_contents($string);
             // TODO: use Guzzle
             $output->writeln('Sending result for URI: ' . $string);
             $resultsQueue->send($userData);
         }
     }
 }
开发者ID:highestgoodlikewater,项目名称:spider-5,代码行数:28,代码来源:HttpWorker.php

示例4: notify

 /**
  * Notifies the task manager given a message constant, see MESSAGE_* constants.
  *
  * @param string $message
  *
  * @return mixed|null The return value of the task manager.
  *
  * @throws RuntimeException in case notification did not occur within the timeout.
  */
 public function notify($message)
 {
     try {
         $command = $this->createCommand($message);
         $this->socket->send($command);
         $result = false;
         $limit = microtime(true) + $this->timeout;
         while (microtime(true) < $limit && false === ($result = $this->socket->recv(\ZMQ::MODE_NOBLOCK))) {
             usleep(1000);
         }
         if (false === $result) {
             $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout));
             throw new RuntimeException('Unable to retrieve information.');
         }
         $data = @json_decode($result, true);
         if (JSON_ERROR_NONE !== json_last_error()) {
             throw new RuntimeException('Invalid task manager response : invalid JSON.');
         }
         if (!isset($data['reply']) || !isset($data['request']) || $command !== $data['request']) {
             throw new RuntimeException('Invalid task manager response : missing fields.');
         }
         return $data['reply'];
     } catch (\ZMQSocketException $e) {
         $this->logger->error(sprintf('Unable to notify the task manager with message "%s" within timeout of %d seconds', $message, $this->timeout), ['exception' => $e]);
         throw new RuntimeException('Unable to retrieve information.', $e->getCode(), $e);
     }
 }
开发者ID:luisbrito,项目名称:Phraseanet,代码行数:36,代码来源:Notifier.php

示例5: broker_task

function broker_task()
{
    //  Prepare our context and sockets
    $context = new ZMQContext();
    $frontend = new ZMQSocket($context, ZMQ::SOCKET_ROUTER);
    $backend = new ZMQSocket($context, ZMQ::SOCKET_ROUTER);
    $frontend->bind("tcp://*:5555");
    $backend->bind("tcp://*:5556");
    //  Initialize poll set
    $poll = new ZMQPoll();
    $poll->add($frontend, ZMQ::POLL_IN);
    $poll->add($backend, ZMQ::POLL_IN);
    $read = $write = array();
    while (true) {
        $events = $poll->poll($read, $write);
        foreach ($read as $socket) {
            $zmsg = new Zmsg($socket);
            $zmsg->recv();
            if ($socket === $frontend) {
                $zmsg->push("W");
                $zmsg->set_socket($backend)->send();
            } elseif ($socket === $backend) {
                $zmsg->pop();
                $zmsg->push("C");
                $zmsg->set_socket($frontend)->send();
            }
        }
    }
}
开发者ID:inactivist,项目名称:zguide,代码行数:29,代码来源:tripping.php

示例6: listen

 /**
  * Start the worker and wait for requests
  */
 public function listen()
 {
     $context = new \ZMQContext();
     $server = new \ZMQSocket($context, \ZMQ::SOCKET_PULL);
     $server->bind('tcp://127.0.0.1:' . ($this->defaultPort + $this->client->getId() - 1));
     $this->logger->info('Client worker ' . $this->client . ' is ready');
     while (true) {
         $request = $server->recv();
         $this->logger->debug('Client worker ' . $this->client . ' receiving request : ' . $request);
         // Check if the input is valid, ignore if wrong
         $request = json_decode($request, true);
         if (!$this->isValidInput($request)) {
             $this->logger->error('Client worker ' . $this->client . ' received an invalid input');
             continue;
         }
         try {
             // Call the right method in the client and push to redis the result
             $result = call_user_func_array(array($this->client, $request['command']), $request['parameters']);
         } catch (ClientNotReadyException $e) {
             $this->logger->warning('Client worker ' . $this->client . ' received a request (#' . $request['invokeId'] . ') whereas the client is not ready. This is normal in case of client reconnection process. Ignoring.');
             continue;
         }
         $key = $this->key . '.client.commands.' . $request['invokeId'];
         $this->redis->rpush($key, serialize($result));
         $this->redis->expire($key, $this->expire);
     }
 }
开发者ID:phxlol,项目名称:lol-php-api,代码行数:30,代码来源:ClientWorker.php

示例7: createPublisher

 /**
  * @param $context
  * @param $endpoint
  * @return Zmsg
  */
 private function createPublisher($context, $endpoint)
 {
     $publisher = new \ZMQSocket($context, \ZMQ::SOCKET_PUB);
     $publisher->setSockOpt(\ZMQ::SOCKOPT_SNDHWM, 1);
     $publisher->connect($endpoint);
     return new Zmsg($publisher);
 }
开发者ID:limitium,项目名称:zmq,代码行数:12,代码来源:ConcentratorTest.php

示例8: close

 /**
  * {@inheritdoc}
  */
 public function close()
 {
     if ($this->socket instanceof \ZMQSocket && !$this->socket->isPersistent()) {
         $this->socket->disconnect($this->dsn);
     }
     $this->socket = null;
 }
开发者ID:bankiru,项目名称:monolog-logstash,代码行数:10,代码来源:ZMQHandler.php

示例9: collect

 public function collect(OutputInterface $output)
 {
     $context = new \ZMQContext();
     $resultsQueue = new \ZMQSocket($context, \ZMQ::SOCKET_PULL);
     $resultsQueue->bind(Spider::ZMQ_RESULTS_QUEUE_BIND_DSN);
     $statusQueue = new \ZMQSocket($context, \ZMQ::SOCKET_PUSH);
     $statusQueue->bind(Spider::ZMQ_STATUS_QUEUE_BIND_DSN);
     $tstart = microtime(true);
     $collectedResults = 0;
     $expectedResults = PHP_INT_MAX;
     $output->writeln('Collecting Task results');
     while ($collectedResults < $expectedResults) {
         $string = $resultsQueue->recv();
         if ($string === Spider::ZMQ_COMMAND_BATCH_START) {
             //  Wait for start of batch
         } elseif (stripos($string, Spider::ZMQ_COMMAND_BATCH_END) === false) {
             $output->writeln('Got task result: ' . substr($string, 0, 20) . ' ...');
             file_put_contents($this->resultsTargetPath . '/' . md5($string) . '.result', $string);
             // TODO: use Symfony/Filesystem
             $output->writeln('Collected results so far: ' . ++$collectedResults);
         } else {
             $expectedResults = (int) explode('%', $string)[1];
             $output->writeln('[INFO] Trying to collect ' . $expectedResults . ' as requested by Task Loader');
         }
     }
     $tend = microtime(true);
     $totalMsec = ($tend - $tstart) * 1000;
     $output->writeln('Task results collecting finished. Got ' . $collectedResults . ' results');
     $output->writeln("Total elapsed time: {$totalMsec} msec");
     $output->writeln('Sending Task Result Collector info');
     $statusQueue->send($collectedResults);
 }
开发者ID:highestgoodlikewater,项目名称:spider-5,代码行数:32,代码来源:TaskResultCollector.php

示例10: run

 /**
  * Run ZMQ interface for generator
  * 
  * Req-rep pattern; msgs are commands:
  * 
  * GEN    = Generate ID
  * STATUS = Get status string
  */
 public function run()
 {
     $context = new \ZMQContext();
     $receiver = new \ZMQSocket($context, \ZMQ::SOCKET_REP);
     $bindTo = 'tcp://*:' . $this->port;
     echo "Binding to {$bindTo}\n";
     $receiver->bind($bindTo);
     while (TRUE) {
         $msg = $receiver->recv();
         switch ($msg) {
             case 'GEN':
                 try {
                     $response = $this->generator->generate();
                 } catch (\Exception $e) {
                     $response = "ERROR";
                 }
                 break;
             case 'STATUS':
                 $response = json_encode($this->generator->status());
                 break;
             default:
                 $response = 'UNKNOWN COMMAND';
                 break;
         }
         $receiver->send($response);
     }
 }
开发者ID:Minds,项目名称:cruftflake,代码行数:35,代码来源:ZeroMq.php

示例11: connect

 public function connect()
 {
     $context = new \ZMQContext();
     $socket = new \ZMQSocket($context, \ZMQ::SOCKET_SUB);
     $socket->bind($this->dsn());
     return $socket;
 }
开发者ID:pelim,项目名称:laravel-zmq,代码行数:7,代码来源:ZmqSubscribe.php

示例12: getSocket

 /**
  * @return \ZMQSocket
  */
 private function getSocket()
 {
     if (null == $this->pushSocket) {
         $this->pushSocket = $this->context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
         $this->pushSocket->connect("tcp://localhost:5555");
     }
     return $this->pushSocket;
 }
开发者ID:Bit-Wasp,项目名称:payment-requests,代码行数:11,代码来源:RequestApi.php

示例13: createCollector

 /**
  * @param $context
  * @param $endpoint
  * @return Zmsg
  */
 private function createCollector($context, $endpoint)
 {
     $receiver = new \ZMQSocket($context, \ZMQ::SOCKET_SUB);
     $receiver->setSockOpt(\ZMQ::SOCKOPT_LINGER, 0);
     $receiver->setSockOpt(\ZMQ::SOCKOPT_SUBSCRIBE, "");
     $receiver->bind($endpoint);
     return $receiver;
 }
开发者ID:limitium,项目名称:zmq,代码行数:13,代码来源:LogTest.php

示例14: it_sends_message_and_gets_response

 /**
  * @test
  */
 public function it_sends_message_and_gets_response()
 {
     $socket = new \ZMQSocket(new \ZMQContext(), \ZMQ::SOCKET_REQ);
     $zmqClient = new ZeroMQSocket($socket, 'tcp://localhost:5556');
     $zmqClient->send($message = 'testing-123');
     $this->assertEquals($message, $zmqClient->receive());
     $socket->disconnect('tcp://localhost:5556');
 }
开发者ID:sandrokeil,项目名称:psb-zeromq-producer,代码行数:11,代码来源:ZeroMQSocketTest.php

示例15: createSubscriber

 /**
  * @param $context
  * @param $endpoint
  * @return Zmsg
  */
 private function createSubscriber($context, $endpoint)
 {
     $receiver = new \ZMQSocket($context, \ZMQ::SOCKET_SUB);
     $receiver->setSockOpt(\ZMQ::SOCKOPT_LINGER, 0);
     $receiver->setSockOpt(\ZMQ::SOCKOPT_SUBSCRIBE, "");
     $receiver->connect($endpoint);
     return new Zmsg($receiver);
 }
开发者ID:limitium,项目名称:zmq,代码行数:13,代码来源:PublisherTest.php


注:本文中的ZMQSocket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。