ZMQ

目录

简介

类摘要

ZMQ

class ZMQ {

/* Constants */

const integer ZMQ::SOCKET_PAIR ;

const integer ZMQ::SOCKET_PUB ;

const integer ZMQ::SOCKET_SUB ;

const integer ZMQ::SOCKET_REQ ;

const integer ZMQ::SOCKET_REP ;

const integer ZMQ::SOCKET_XREQ ;

const integer ZMQ::SOCKET_XREP ;

const integer ZMQ::SOCKET_PUSH ;

const integer ZMQ::SOCKET_PULL ;

const integer ZMQ::SOCKET_ROUTER ;

const integer ZMQ::SOCKET_DEALER ;

const integer ZMQ::SOCKET_XPUB ;

const integer ZMQ::SOCKET_XSUB ;

const integer ZMQ::SOCKET_STREAM ;

const integer ZMQ::SOCKOPT_HWM ;

const integer ZMQ::SOCKOPT_SNDHWM ;

const integer ZMQ::SOCKOPT_RCVHWM ;

const integer ZMQ::SOCKOPT_AFFINITY ;

const integer ZMQ::SOCKOPT_IDENTITY ;

const integer ZMQ::SOCKOPT_SUBSCRIBE ;

const integer ZMQ::SOCKOPT_UNSUBSCRIBE ;

const integer ZMQ::SOCKOPT_RATE ;

const integer ZMQ::SOCKOPT_RECOVERY_IVL ;

const integer ZMQ::SOCKOPT_RECONNECT_IVL ;

const integer ZMQ::SOCKOPT_RECONNECT_IVL_MAX ;

const integer ZMQ::SOCKOPT_MCAST_LOOP ;

const integer ZMQ::SOCKOPT_SNDBUF ;

const integer ZMQ::SOCKOPT_RCVBUF ;

const integer ZMQ::SOCKOPT_RCVMORE ;

const integer ZMQ::SOCKOPT_TYPE ;

const integer ZMQ::SOCKOPT_LINGER ;

const integer ZMQ::SOCKOPT_BACKLOG ;

const integer ZMQ::SOCKOPT_MAXMSGSIZE ;

const integer ZMQ::SOCKOPT_SNDTIMEO ;

const integer ZMQ::SOCKOPT_RCVTIMEO ;

const integer ZMQ::SOCKOPT_IPV4ONLY ;

const integer ZMQ::SOCKOPT_LAST_ENDPOINT ;

const integer ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE ;

const integer ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT ;

const integer ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL ;

const integer ZMQ::SOCKOPT_TCP_ACCEPT_FILTER ;

const integer ZMQ::SOCKOPT_TCP_ACCEPT_FILTER ;

const integer ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT ;

const integer ZMQ::SOCKOPT_XPUB_VERBOSE ;

const integer ZMQ::SOCKOPT_ROUTER_RAW ;

const integer ZMQ::SOCKOPT_IPV6 ;

const integer ZMQ::CTXOPT_MAX_SOCKETS ;

const integer ZMQ::POLL_IN ;

const integer ZMQ::POLL_OUT ;

const integer ZMQ::MODE_NOBLOCK ;

const integer ZMQ::MODE_DONTWAIT ;

const integer ZMQ::MODE_SNDMORE ;

const integer ZMQ::ERR_INTERNAL ;

const integer ZMQ::ERR_EAGAIN ;

const integer ZMQ::ERR_ENOTSUP ;

const integer ZMQ::ERR_EFSM ;

const integer ZMQ::ERR_ETERM ;

/* Methods */

private __construct ( void )

}

预定义常量

ZMQ Constant Types

ZMQ::SOCKET_PAIR
Exclusive pair pattern

ZMQ::SOCKET_PUB
Publisher socket

ZMQ::SOCKET_SUB
Subscriber socket

ZMQ::SOCKET_REQ
Request socket

ZMQ::SOCKET_REP
Reply socket

ZMQ::SOCKET_XREQ
Alias for SOCKET_DEALER

ZMQ::SOCKET_XREP
Alias for SOCKET_ROUTER

ZMQ::SOCKET_PUSH
Pipeline upstream push socket

ZMQ::SOCKET_PULL
Pipeline downstream pull socket

ZMQ::SOCKET_ROUTER
Extended REP socket that can route replies to requesters

ZMQ::SOCKET_DEALER
Extended REQ socket that load balances to all connected peers

ZMQ::SOCKET_XPUB
Similar to SOCKET_PUB, except you can receive subscriptions as messages. The subscription message is 0 (unsubscribe) or 1 (subscribe) followed by the topic.

ZMQ::SOCKET_XSUB
Similar to SOCKET_SUB, except you can send subscriptions as messages. See SOCKET_XPUB for format.

ZMQ::SOCKET_STREAM
Used to send and receive TCP data from a non-ØMQ peer. Available if compiled against ZeroMQ 4.x or higher (Value: integer).

ZMQ::SOCKOPT_HWM
The high water mark for inbound and outbound messages is a hard limit on the maximum number of outstanding messages ØMQ shall queue in memory for any single peer that the specified socket is communicating with. Setting this option on a socket will only affect connections made after the option has been set. On ZeroMQ 3.x this is a wrapper for setting both SNDHWM and RCVHWM. (Value: integer).

ZMQ::SOCKOPT_SNDHWM
The ZMQ_SNDHWM option shall set the high water mark for outbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_RCVHWM
The SOCKOPT_RCVHWM option shall set the high water mark for inbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_AFFINITY
Set I/O thread affinity (Value: integer)

ZMQ::SOCKOPT_IDENTITY
Set socket identity (Value: string)

ZMQ::SOCKOPT_SUBSCRIBE
Establish message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_UNSUBSCRIBE
Remove message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_RATE
Set rate for multicast sockets (pgm) (Value: integer >= 0)

ZMQ::SOCKOPT_RECOVERY_IVL
Set multicast recovery interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL
Set the initial reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL_MAX
Set the max reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_MCAST_LOOP
Control multicast loopback (Value: integer >= 0)

ZMQ::SOCKOPT_SNDBUF
Set kernel transmit buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVBUF
Set kernel receive buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVMORE
Receive multi-part messages (Value: integer)

ZMQ::SOCKOPT_TYPE
Get the socket type. Valid for getSockOpt (Value: integer)

ZMQ::SOCKOPT_LINGER
The linger value of the socket. Specifies how long the socket blocks trying flush messages after it has been closed (Value: integer)

ZMQ::SOCKOPT_BACKLOG
The SOCKOPT_BACKLOG option shall set the maximum length of the queue of outstanding peer connections for the specified socket; this only applies to connection-oriented transports. (Value: integer)

ZMQ::SOCKOPT_MAXMSGSIZE
Limits the maximum size of the inbound message. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_SNDTIMEO
Sets the timeout for send operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_RCVTIMEO
Sets the timeout for receive operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_IPV4ONLY
Disable IPV6 support if 1. Available if compiled against ZeroMQ 3.x (Value: integer)

ZMQ::SOCKOPT_LAST_ENDPOINT
Retrieve the last connected endpoint - for use with * wildcard ports. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE
Idle time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT
Count time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL
Interval for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT
Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_ACCEPT_FILTER
Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_XPUB_VERBOSE
Set the XPUB to receive an application message on each instance of a subscription. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_ROUTER_RAW
Sets the raw mode on the ROUTER, when set to 1. In raw mode when using tcp:// transport the socket will read and write without ZeroMQ framing. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::SOCKOPT_IPV6
Enable IPV6. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::CTXOPT_MAX_SOCKETS
The socket limit for this context. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::POLL_IN
Poll for incoming data

ZMQ::POLL_OUT
Poll for outgoing data

ZMQ::MODE_NOBLOCK
Non-blocking operation. Deprecated, use ZMQ::MODE_DONTWAIT instead

ZMQ::MODE_DONTWAIT
Non-blocking operation

ZMQ::MODE_SNDMORE
Send multi-part message

ZMQ::DEVICE_FORWARDER
Forwarder device

ZMQ::DEVICE_QUEUE
Queue device

ZMQ::DEVICE_STREAMER
Streamer device

ZMQ::ERR_INTERNAL
ZMQ extension internal error

ZMQ::ERR_EAGAIN
Implies that the operation would block when ZMQ::MODE_DONTWAIT is used

ZMQ::ERR_ENOTSUP
The operation is not supported by the socket type

ZMQ::ERR_EFSM
The operation can not be executed because the socket is not in correct state

ZMQ::ERR_ETERM
The context has been terminated

ZMQ::__construct

ZMQ constructor

说明

private ZMQ::__construct ( void )

Private constructor to prevent direct initialization. This class holds the constants for ZMQ extension.

参数

此函数没有参数。

返回值

简介

类摘要

ZMQContext

class ZMQContext {

/* Methods */

__construct ([ int $io_threads = 1 [, bool $is_persistent = TRUE ]] )

public mixed getOpt ( string $key )

public ZMQSocket getSocket ( int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )

public bool isPersistent ( void )

public ZMQContext setOpt ( int $key , mixed $value )

}

ZMQContext::__construct

Construct a new ZMQContext object

说明

ZMQContext::__construct ([ int $io_threads = 1 [, bool $is_persistent = TRUE ]] )

Constructs a new ZMQ context. The context is used to initialize sockets. A persistent context is required to initialize persistent sockets.

参数

io_threads
Number of io-threads in the context.

is_persistent
Whether the context is persistent. Persistent context is stored over multiple requests and is a requirement for persistent sockets.

范例

示例 #1 A ZMQContext example

Construct a new context and allocate request socket from it

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
?>

返回值

Throws ZMQContextException if context initialization fails.

ZMQContext::getOpt

Get context option

说明

public mixed ZMQContext::getOpt ( string $key )

Returns the value of a context option.

参数

key
An integer representing the option. See the ZMQ::CTXOPT_* constants.

返回值

Returns either a string or an integer depending on key. Throws ZMQContextException on error.

ZMQContext::getSocket

Create a new socket

说明

public ZMQSocket ZMQContext::getSocket ( int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )

Shortcut for creating new sockets from the context. If the context is not persistent the persistent_id parameter is ignored and the socket falls back to being non-persistent. The on_new_socket is called only when a new underlying socket structure is created.

参数

type
ZMQ::SOCKET_* constant to specify socket type.

persistent_id
If persistent_id is specified the socket will be persisted over multiple requests.

on_new_socket
Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used. The callback takes ZMQSocket and persistent_id as two arguments.

范例

示例 #1 A ZMQContext example

Basic usage

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
echo "Received message: {$message}\n";
?>

返回值

Returns a ZMQSocket object on success. Throws ZMQSocketException on error.

ZMQContext::isPersistent

Whether the context is persistent

说明

public bool ZMQContext::isPersistent ( void )

Whether the context is persistent. Persistent context is needed for persistent connections as each socket is allocated from a context.

参数

此函数没有参数。

返回值

Returns TRUE if the context is persistent and FALSE if the context is non-persistent.

ZMQContext::setOpt

Set a socket option

说明

public ZMQContext ZMQContext::setOpt ( int $key , mixed $value )

Sets a ZMQ context option. The type of the value depends on the key. See ZMQ Constant Types for more information.

参数

key
One of the ZMQ::CTXOPT_* constants.

value
The value of the parameter.

返回值

Returns the current object. Throws ZMQContextException on error.

简介

类摘要

ZMQSocket

class ZMQSocket {

/* Methods */

public ZMQSocket bind ( string $dsn [, bool $force = FALSE ] )

public ZMQSocket connect ( string $dsn [, bool $force = FALSE ] )

__construct ( ZMQContext $context , int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )

public ZMQSocket disconnect ( string $dsn )

public array getEndpoints ( void )

public string getPersistentId ( void )

public int getSocketType ( void )

public mixed getSockOpt ( string $key )

public bool isPersistent ( void )

public string recv ([ int $mode = 0 ] )

public array recvMulti ([ int $mode = 0 ] )

public ZMQSocket send ( string $message [, int $mode = 0 ] )

public ZMQSocket sendmulti ( array $message [, int $mode = 0 ] )

public ZMQSocket setSockOpt ( int $key , mixed $value )

public ZMQSocket unbind ( string $dsn )

}

ZMQSocket::bind

Bind the socket

说明

public ZMQSocket ZMQSocket::bind ( string $dsn [, bool $force = FALSE ] )

Bind the socket to an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn
The bind dsn, for example transport://address.

force
Tries to bind even if the socket has already been bound to the given endpoint.

返回值

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::connect

Connect the socket

说明

public ZMQSocket ZMQSocket::connect ( string $dsn [, bool $force = FALSE ] )

Connect the socket to a remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn
The connect dsn, for example transport://address.

force
Tries to connect even if the socket has already been connected to given endpoint.

范例

示例 #1 A ZMQContext example

Construct a new context and allocate request socket from it

<?php
/* Server hostname */
$dsn = "tcp://127.0.0.1:5555";

/* Create a socket */
$socket = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, 'my socket');

/* Get list of connected endpoints */
$endpoints = $socket->getEndpoints();

/* Check if the socket is connected */
if (!in_array($dsn, $endpoints['connect'])) {
    echo "<p>Connecting to $dsn</p>";
    $socket->connect($dsn);
} else {
    echo "<p>Already connected to $dsn</p>";
}

/* Send and receive */
$socket->send("Hello!");
$message = $socket->recv();

echo "<p>Server said: {$message}</p>";
?>

返回值

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::__construct

Construct a new ZMQSocket

说明

ZMQSocket::__construct ( ZMQContext $context , int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )

Constructs a ZMQSocket object. persistent_id parameter can be used to allocated a persistent socket. A persistent socket has to be allocated from a persistent context and it stays connected over multiple requests. The persistent_id parameter can be used to recall the same socket over multiple requests. The on_new_socket is called only when a new underlying socket structure is created.

参数

context
ZMQContext object.

type
The socket type. See ZMQ::SOCKET_* constants.

persistent_id
If persistent_id is specified the socket will be persisted over multiple requests. If context is not persistent the socket falls back to non-persistent mode.

on_new_socket
Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used.

范例

示例 #1 A ZMQSocket example

Using callback the bind/connect socket

<?php

/*
  The socket is persistent so this function is called only on the 
  first request to the script.
*/
function on_new_socket_cb(ZMQSocket $socket, $persistent_id = null)
{
    if ($persistent_id === 'server') {
        $socket->bind("tcp://localhost:12122");
    } else {
        $socket->connect("tcp://localhost:12122");
    }
}

/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REP, 'server', 'on_new_socket_cb');

$message = $socket->recv();
echo "Received message: {$message}\n";
?>

The callback signature

Note:

function on_new_socket_cb(ZMQSocket $socket, string $persistent_id = null);

返回值

Throws ZMQSocketException on error.

ZMQSocket::disconnect

Disconnect a socket

说明

public ZMQSocket ZMQSocket::disconnect ( string $dsn )

Disconnect the socket from a previously connected remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn
The connect dsn, for example transport://address.

返回值

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::getEndpoints

Get list of endpoints

说明

public array ZMQSocket::getEndpoints ( void )

Returns a list of endpoints where the socket is connected or bound to.

参数

此函数没有参数。

返回值

Returns an array containing elements 'bind' and 'connect'.

ZMQSocket::getPersistentId

Get the persistent id

说明

public string ZMQSocket::getPersistentId ( void )

Returns the persistent id of the socket.

参数

此函数没有参数。

返回值

Returns the persistent id string assigned of the object and NULL if socket is not persistent.

ZMQSocket::getSocketType

Get the socket type

说明

public int ZMQSocket::getSocketType ( void )

Gets the socket type.

参数

此函数没有参数。

返回值

Returns an integer representing the socket type. The integer can be compared against ZMQ::SOCKET_* constants.

ZMQSocket::getSockOpt

Get socket option

说明

public mixed ZMQSocket::getSockOpt ( string $key )

Returns the value of a socket option.

参数

key
An integer representing the option. See the ZMQ::SOCKOPT_* constants.

返回值

Returns either a string or an integer depending on key. Throws ZMQSocketException on error.

ZMQSocket::isPersistent

Whether the socket is persistent

说明

public bool ZMQSocket::isPersistent ( void )

Check whether the socket is persistent.

参数

此函数没有参数。

返回值

Returns a boolean based on whether the socket is persistent or not.

ZMQSocket::recv

Receives a message

说明

public string ZMQSocket::recv ([ int $mode = 0 ] )

Receive a message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_DONTWAIT flag is used. ZMQ::SOCKOPT_RCVMORE socket option can be used for receiving multi-part messages. See ZMQSocket::setSockOpt for more information.

参数

mode
Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

范例

示例 #1 A send/recv example

Non-blocking send / receive

<?php

/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");

/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;

/* Start a loop */
do {
    try {
        /* Try to send / receive */
        if ($sending) {
            echo "Sending message\n";
            $queue->send("This is a message", ZMQ::MODE_DONTWAIT);
            $sending = false;
        } else {
            echo "Got response: " . $queue->recv(ZMQ::MODE_DONTWAIT) . "\n";
            break;
        }
    } catch (ZMQSocketException $e) {
        /* EAGAIN means that the operation would have blocked, retry */
        if ($e->getCode() === ZMQ::ERR_EAGAIN) {
            echo " - Got EAGAIN, retrying ($retries)\n";
        } else {
            die(" - Error: " . $e->getMessage());
        }
    }
    /* Sleep a bit between operations */
    usleep(5);
} while (--$retries);
?>

以上例程的输出类似于:

Sending message
 - Unable to execute operation, retrying (4)
Got response: This is a message

返回值

Returns the message. Throws ZMQSocketException in error. If ZMQ::MODE_DONTWAIT is used and the operation would block boolean false shall be returned.

ZMQSocket::recvMulti

Receives a multipart message

说明

public array ZMQSocket::recvMulti ([ int $mode = 0 ] )

Receive an array multipart message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used.

参数

mode
Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the array of message parts. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::send

Sends a message

说明

public ZMQSocket ZMQSocket::send ( string $message [, int $mode = 0 ] )

Send a message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

参数

message
The message to send.

mode
Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::sendmulti

Sends a multipart message

说明

public ZMQSocket ZMQSocket::sendmulti ( array $message [, int $mode = 0 ] )

Send a multipart message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

参数

message
The message to send - an array of strings

mode
Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.

ZMQSocket::setSockOpt

Set a socket option

说明

public ZMQSocket ZMQSocket::setSockOpt ( int $key , mixed $value )

Sets a ZMQ socket option. The type of the value depends on the key. See ZMQ Constant Types for more information.

参数

key
One of the ZMQ::SOCKOPT_* constants.

value
The value of the parameter.

返回值

Returns the current object. Throws ZMQSocketException on error.

ZMQSocket::unbind

Unbind the socket

说明

public ZMQSocket ZMQSocket::unbind ( string $dsn )

Unbind the socket from an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn
The previously bound dsn, for example transport://address.

返回值

Returns the current object. Throws ZMQSocketException on error.

简介

类摘要

ZMQPoll

class ZMQPoll {

/* Methods */

public string add ( mixed $entry , int $type )

public ZMQPoll clear ( void )

public int count ( void )

public array getLastErrors ( void )

public int poll ( array &$readable , array &$writable [, int $timeout = -1 ] )

public bool remove ( mixed $item )

}

ZMQPoll::add

Add item to the poll set

说明

public string ZMQPoll::add ( mixed $entry , int $type )

Adds a new item to the poll set and returns the internal id of the added item. The item can be removed from the poll set using the returned string id.

参数

entry
ZMQSocket object or a PHP stream resource

type
Defines what activity the socket is polled for. See ZMQ::POLL_IN and ZMQ::POLL_OUT constants.

返回值

Returns a string id of the added item which can be later used to remove the item. Throws ZMQPollException on error.

ZMQPoll::clear

Clear the poll set

说明

public ZMQPoll ZMQPoll::clear ( void )

Clears all elements from the poll set.

参数

此函数没有参数。

返回值

Returns the current object.

ZMQPoll::count

Count items in the poll set

说明

public int ZMQPoll::count ( void )

Count the items in the poll set.

参数

此函数没有参数。

返回值

Returns an integer representing the amount of items in the poll set.

ZMQPoll::getLastErrors

Get poll errors

说明

public array ZMQPoll::getLastErrors ( void )

Returns the ids of the objects that had errors in the last poll.

参数

此函数没有参数。

返回值

Returns an array containing ids for the items that had errors in the last poll. Empty array is returned if there were no errors.

ZMQPoll::poll

Poll the items

说明

public int ZMQPoll::poll ( array &$readable , array &$writable [, int $timeout = -1 ] )

Polls the items in the current poll set. The readable and writable items are returned in the readable and writable parameters. ZMQPoll::getLastErrors can be used to check if there were errors.

参数

readable
Array where readable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

writable
Array where writable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

timeout
Timeout for the operation. -1 means that poll waits until at least one item has activity. Please note that starting from version 1.0.0 the poll timeout is defined in milliseconds, rather than microseconds.

范例

示例 #1 A ZMQPoll example

Create a simple poll server

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server  = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo "Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (true) {
   /* Amount of events retrieved */
   $events = 0;

   try {
       /* Poll until there is something to do */
       $events = $poll->poll($readable, $writable, -1);
       $errors = $poll->getLastErrors();

       if (count($errors) > 0) {
           foreach ($errors as $error) {
               echo "Error polling object " . $error . "\n";
           }
       }
   } catch (ZMQPollException $e) {
       echo "poll failed: " . $e->getMessage() . "\n";
   }

   if ($events > 0) {
       /* Loop through readable objects and recv messages */
       foreach ($readable as $r) {
           try {
               echo "Received message: " . $r->recv() . "\n";
           } catch (ZMQException $e) {
               echo "recv failed: " . $e->getMessage() . "\n";
           }
       }

       /* Loop through writable and send back messages */
       foreach ($writable as $w) {
           try {
               $w->send("Got it!");
           } catch (ZMQException $e) {
               echo "send failed: " . $e->getMessage() . "\n";
           }
       }
   }
}
?>

返回值

Returns an integer representing amount of items with activity. Throws ZMQPollException on error.

ZMQPoll::remove

Remove item from poll set

说明

public bool ZMQPoll::remove ( mixed $item )

Remove item from the poll set. The item parameter can be ZMQSocket object, a stream resource or the id returned from ZMQPoll::add method.

参数

item
The ZMQSocket object, PHP stream or string id of the item.

返回值

Returns true if the item was removed and false if the object with given id does not exist in the poll set.

简介

类摘要

ZMQDevice

class ZMQDevice {

/* Methods */

__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )

public ZMQDevice getIdleTimeout ( void )

public ZMQDevice getTimerTimeout ( void )

public void run ( void )

public ZMQDevice setIdleCallback ( callable $cb_func , int $timeout [, mixed $user_data ] )

public ZMQDevice setIdleTimeout ( int $timeout )

public ZMQDevice setTimerCallback ( callable $cb_func , int $timeout [, mixed $user_data ] )

public ZMQDevice setTimerTimeout ( int $timeout )

}

ZMQDevice::__construct

Construct a new device

说明

ZMQDevice::__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )

"ØMQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers." -- zguide

参数

frontend
Frontend parameter for the devices. Usually where there messages are coming.

backend
Backend parameter for the devices. Usually where there messages going to.

listener
Listener socket, which receives a copy of all messages going both directions. The type of this socket should be SUB, PULL or DEALER.

返回值

Call to this method will prepare the device. Usually devices are very long running processes so running this method from interactive script is not recommended. This method throw ZMQDeviceException if the device cannot be started.

ZMQDevice::getIdleTimeout

Get the idle timeout

说明

public ZMQDevice ZMQDevice::getIdleTimeout ( void )

Gets the idle callback timeout value. Added in ZMQ extension version 1.1.0.

返回值

This method returns the idle callback timeout value.

ZMQDevice::getTimerTimeout

Get the timer timeout

说明

public ZMQDevice ZMQDevice::getTimerTimeout ( void )

Gets the timer callback timeout value. Added in ZMQ extension version 1.1.0.

返回值

This method returns the timer timeout value.

ZMQDevice::run

Run the new device

说明

public void ZMQDevice::run ( void )

Runs the device.

参数

此函数没有参数。

返回值

Call to this method will block until the device is running. It is not recommended that devices are used from interactive scripts. On failure this method will throw ZMQDeviceException.

ZMQDevice::setIdleCallback

Set the idle callback function

说明

public ZMQDevice ZMQDevice::setIdleCallback ( callable $cb_func , int $timeout [, mixed $user_data ] )

Sets the idle callback function. If idle timeout is defined the idle callback function shall be called if the internal poll loop times out without events. If the callback function returns false or a value that evaluates to false the device is stopped. The callback function signature is callback (mixed $user_data).

参数

cb_func
Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout
How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data
Additional data to pass to the callback function.

返回值

On success this method returns the current object.

ZMQDevice::setIdleTimeout

Set the idle timeout

说明

public ZMQDevice ZMQDevice::setIdleTimeout ( int $timeout )

Sets the idle callback timeout value. The idle callback is invoked periodically when the device is idle.

参数

timeout
The idle callback timeout value.

返回值

On success this method returns the current object.

ZMQDevice::setTimerCallback

Set the timer callback function

说明

public ZMQDevice ZMQDevice::setTimerCallback ( callable $cb_func , int $timeout [, mixed $user_data ] )

Sets the timer callback function. The timer callback will be invoked after timeout has passed. The difference between idle and timer callbacks are that idle callback is invoked only when the device is idle. The callback function signature is callback (mixed $user_data). Added in ZMQ extension version 1.1.0.

参数

cb_func
Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout
How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data
Additional data to pass to the callback function.

返回值

On success this method returns the current object.

ZMQDevice::setTimerTimeout

Set the timer timeout

说明

public ZMQDevice ZMQDevice::setTimerTimeout ( int $timeout )

Sets the timer callback timeout value. The timer callback is invoked periodically if it's set. Added in ZMQ extension version 1.1.0.

参数

timeout
The timer callback timeout value.

返回值

On success this method returns the current object.