本文整理汇总了PHP中ZMQSocket::recv方法的典型用法代码示例。如果您正苦于以下问题:PHP ZMQSocket::recv方法的具体用法?PHP ZMQSocket::recv怎么用?PHP ZMQSocket::recv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZMQSocket
的用法示例。
在下文中一共展示了ZMQSocket::recv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: client_task
function client_task()
{
$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_DEALER);
$client->setSockOpt(ZMQ::SOCKOPT_IDENTITY, "C");
$client->connect("tcp://localhost:5555");
echo "Setting up test...", PHP_EOL;
usleep(10000);
echo "Synchronous round-trip test...", PHP_EOL;
$start = microtime(true);
$text = "HELLO";
for ($requests = 0; $requests < 10000; $requests++) {
$client->send($text);
$msg = $client->recv();
}
printf(" %d calls/second%s", 1000 * 10000 / (int) ((microtime(true) - $start) * 1000), PHP_EOL);
echo "Asynchronous round-trip test...", PHP_EOL;
$start = microtime(true);
for ($requests = 0; $requests < 100000; $requests++) {
$client->send($text);
}
for ($requests = 0; $requests < 100000; $requests++) {
$client->recv();
}
printf(" %d calls/second%s", 1000 * 100000 / (int) ((microtime(true) - $start) * 1000), PHP_EOL);
}
示例2: 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);
}
}
示例3: recv
/**
* Receive message from socket
* Creates a new message and returns it
* Blocks on recv if socket is not ready for input
*
* @throws Exception if no socket present
* @return Zmsg
*/
public function recv()
{
if (!isset($this->_socket)) {
throw new Exception("No socket supplied");
}
$this->_parts = array();
while (true) {
$this->_parts[] = $this->_socket->recv();
if (!$this->_socket->getSockOpt(ZMQ::SOCKOPT_RCVMORE)) {
break;
}
}
return $this;
}
示例4: startStackWork
/**
* @return null
*/
public function startStackWork()
{
$getTaskDto = new ReplyStackToPulsarGetTaskRequestDto();
$considerMeAsSubscriber = 0;
while (true) {
//$this->logger->debug("Start ReplyStack while.");
$this->pulsarRequestSocket->send(serialize($getTaskDto));
/**Blocking wait reply from Pulsar
* @var PulsarToReplyStackReplyDto $pulsarToReplyStackReplyDto
*/
$pulsarToReplyStackReplyDto = unserialize($this->pulsarRequestSocket->recv());
//$this->logger->debug("REPLY STACK asked to prepare subscribers: " . $pulsarToReplyStackReplyDto->getSubscribersNumber());
for ($i = 1; $i <= $pulsarToReplyStackReplyDto->getSubscribersNumber(); $i++) {
$preparingDto = unserialize($this->performersReplySocket->recv());
//$this->logger->debug("REPLY STACK: receive request $i");
if ($preparingDto instanceof PreparingRequestDto) {
$considerMeAsSubscriber++;
//$this->logger->debug("REPLY STACK: considerMeAsSubscriber: $considerMeAsSubscriber");
$this->performersReplySocket->send(serialize($pulsarToReplyStackReplyDto->getDtoToTransfer()));
}
}
//$this->logger->debug("REPLY STACK prepared subscribers: " . $considerMeAsSubscriber);
$replyStackResult = new ReplyStackToPulsarReturnResultRequestDto();
$replyStackResult->setConsiderMeAsSubscriber($considerMeAsSubscriber);
$this->pulsarRequestSocket->send(serialize($replyStackResult));
//$this->logger->debug("Wait finishing message from Pulsar.");
$this->pulsarRequestSocket->recv();
//$this->logger->debug("Got finish message from Pulsar.");
$considerMeAsSubscriber = 0;
//$this->logger->debug("Finish ReplyStack while.");
}
return null;
}
示例5: 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);
}
}
示例6: 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);
}
示例7: 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);
}
}
示例8: 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);
}
}
}
示例9: receiveMessage
/**
* @param string|null $queueId
* @param int $waitTime
*
* @return QueueMessage
*/
public function receiveMessage($queueId = null, $waitTime = null)
{
$queueId = empty($queueId) ? $this->getQueueId() : $queueId;
$this->setupPullSocket($queueId);
$this->pull->setSockOpt(\ZMQ::SOCKOPT_RCVTIMEO, isset($waitTime) ? $waitTime : $this->waitTime);
$message = $this->pull->recv();
return $this->messageFactory->createMessage($message, $queueId);
}
示例10: client_thread
function client_thread()
{
$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_REQ);
$client->connect("ipc://frontend.ipc");
// Send request, get reply
$client->send("HELLO");
$reply = $client->recv();
printf("Client: %s%s", $reply, PHP_EOL);
}
示例11: checkForExternalCommand
private function checkForExternalCommand()
{
$cmd = $this->zmq_socket->recv(\ZMQ::MODE_NOBLOCK);
if ($cmd != null) {
switch ($cmd) {
case 'refresh jobs':
$this->jobs = $this->schedule->getAllJobs();
$this->zmq_socket->send(1, \ZMQ::MODE_NOBLOCK);
break;
case 'get loaded jobs':
$data = array();
foreach ($this->jobs as $job) {
$data[] = (array) $job;
}
$this->zmq_socket->send(serialize($data), \ZMQ::MODE_NOBLOCK);
break;
}
}
}
示例12: url_hash_worker
function url_hash_worker()
{
// Socket to talk to dispatcher
$context = new ZMQContext();
$receiver = new ZMQSocket($context, ZMQ::SOCKET_REP);
$receiver->connect("ipc://urlhash.ipc");
while (true) {
$hashedUrl = $receiver->recv();
$receiver->send(hashDecode($hashedUrl));
}
}
示例13: 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);
while (true) {
// Send request, get reply
$client->send("HELLO");
$reply = $client->recv();
printf("I: client status: %s%s", $reply, PHP_EOL);
}
}
示例14: array
function __call($name, $arguments)
{
$context = new \ZMQContext();
$zmq = new \ZMQSocket($context, \ZMQ::SOCKET_REQ);
$zmq->connect($this->socket);
$message = array('jsonrpc' => '2.0', 'method' => $name, 'params' => $arguments, 'id' => round(microtime(true) * 100000));
/** @var \ZMQSocket $resultSocket */
$zmq->send(json_encode($message));
$result = json_decode($zmq->recv(), true);
if (isset($result['error'])) {
throw new RpcException($result['exception']['message'], $result['exception']['code']);
}
return $result['result'];
}
示例15: worker_routine
function worker_routine()
{
$context = new ZMQContext();
// Socket to talk to dispatcher
$receiver = new ZMQSocket($context, ZMQ::SOCKET_REP);
$receiver->connect("ipc://workers.ipc");
while (true) {
$string = $receiver->recv();
printf("Received request: [%s]%s", $string, PHP_EOL);
// Do some 'work'
sleep(1);
// Send reply back to client
$receiver->send("World");
}
}