AMQPClassic Class

Properties   Methods   Events   Configuration Settings   Errors  

An easy-to-use AMQP 0.9.1 client implementation, with support for RabbitMQ extensions.

Class Name

IPWorksIoT_AMQPClassic

Procedural Interface

 ipworksiot_amqpclassic_open();
 ipworksiot_amqpclassic_close($res);
 ipworksiot_amqpclassic_register_callback($res, $id, $function);
 ipworksiot_amqpclassic_get_last_error($res);
 ipworksiot_amqpclassic_get_last_error_code($res);
 ipworksiot_amqpclassic_set($res, $id, $index, $value);
 ipworksiot_amqpclassic_get($res, $id, $index);
 ipworksiot_amqpclassic_do_bindqueue($res, $channelname, $queuename, $exchangename, $routingkey, $nowait);
 ipworksiot_amqpclassic_do_cancelconsume($res, $channelname, $consumertag, $nowait);
 ipworksiot_amqpclassic_do_closechannel($res, $channelname);
 ipworksiot_amqpclassic_do_committransaction($res, $channelname);
 ipworksiot_amqpclassic_do_config($res, $configurationstring);
 ipworksiot_amqpclassic_do_connect($res, $host, $port);
 ipworksiot_amqpclassic_do_consume($res, $channelname, $queuename, $consumertag, $nolocal, $noack, $exclusive, $nowait);
 ipworksiot_amqpclassic_do_createchannel($res, $channelname);
 ipworksiot_amqpclassic_do_declareexchange($res, $channelname, $exchangename, $exchangetype, $passive, $durable, $autodelete, $nowait);
 ipworksiot_amqpclassic_do_declarequeue($res, $channelname, $queuename, $passive, $durable, $exclusive, $autodelete, $nowait);
 ipworksiot_amqpclassic_do_deleteexchange($res, $channelname, $exchangename, $ifunused, $nowait);
 ipworksiot_amqpclassic_do_deletequeue($res, $channelname, $queuename, $ifunused, $ifempty, $nowait);
 ipworksiot_amqpclassic_do_disconnect($res);
 ipworksiot_amqpclassic_do_doevents($res);
 ipworksiot_amqpclassic_do_enablepublishconfirms($res, $channelname, $nowait);
 ipworksiot_amqpclassic_do_enabletransactionmode($res, $channelname);
 ipworksiot_amqpclassic_do_fetchmessage($res, $channelname, $queuename, $noack);
 ipworksiot_amqpclassic_do_interrupt($res);
 ipworksiot_amqpclassic_do_publishmessage($res, $channelname, $exchangename, $routingkey, $mandatory, $immediate);
 ipworksiot_amqpclassic_do_purgequeue($res, $channelname, $queuename, $nowait);
 ipworksiot_amqpclassic_do_recover($res, $channelname, $requeue);
 ipworksiot_amqpclassic_do_reset($res);
 ipworksiot_amqpclassic_do_resetmessage($res);
 ipworksiot_amqpclassic_do_rollbacktransaction($res, $channelname);
 ipworksiot_amqpclassic_do_setchannelaccept($res, $channelname, $accept);
 ipworksiot_amqpclassic_do_setqos($res, $channelname, $prefetchsize, $prefetchcount, $global);
 ipworksiot_amqpclassic_do_unbindqueue($res, $channelname, $queuename, $exchangename, $routingkey);

Remarks

The AMQPClassic class provides an easy-to-use AMQP 0.9.1 client implementation, and it also supports certain RabbitMQ extensions to the AMQP 0.9.1 specification. The class supports both plaintext and TLS-enabled connections over TCP.

Connecting

The AMQP 0.9.1 transport protocol has two layers: an overall connection between the client and server, and one or more channels running over that connection.

The class implements both layers, so the first step is to initiate the overall connection. Set the AuthScheme, User, Password, SSLEnabled, and VirtualHost properties if necessary, then call the Connect method, passing it the server's hostname and port number. (If the server in question is not running RabbitMQ, disabling the RabbitMQCompatible configuration setting before connecting is also recommended.)

The next step is to create at least one channel, which can be accomplished by using the CreateChannel method. The class allows creating any number of channels, up to the limit specified by the MaxChannelCount configuration setting.

Connecting and Creating a Channel

// The examples in this documentation use a RabbitMQ server, which requires SASL Plain auth.
amqpc1.AuthScheme = AmqpclassicAuthSchemes.smSASLPlain;
amqpc1.User = "guest";
amqpc1.Password = "guest";
amqpc1.SSLEnabled = true;
amqpc1.Connect("amqpclassic.test-server.com", 5671);
amqpc1.CreateChannel("channel");

Once the class has connected to the server, and one or more channels have been opened, the class can begin manipulating exchanges and queues, publishing messages, and creating consumers.

Note that most AMQP 0.9.1 operations can themselves vary in their complexity. The examples below are intentionally simple for the sake of clarity and brevity, but links are provided for many other parts of the class's API where more detail can be found.

Declaring Exchanges

The DeclareExchange method is used to declare (i.e., create, or verify the existence of) exchanges on the server. While all AMQP servers provide a default, direct-type exchange that all queues are bound to automatically (using their name as the routing key), more complex use-cases will often require creating additional exchanges of varying types.

Declaring an Exchange

// Declare a direct-type exchange.
amqpc1.DeclareExchange("channel", "MyExchange", "direct", false, false, false, false);

Exchanges can also be deleted using the DeleteExchange method.

Declaring Queues

The DeclareQueue method is used to declare (i.e., create, or verify the existence of) queues on the server. Unlike with exchanges, the server does not provide any queues by default, so declaring a queue is always necessary (unless one has already been created by another client, or configured ahead-of-time on the server itself).

Declaring a Queue

// Declare a queue.
amqpc1.DeclareQueue("channel", "MyQueue", false, false, false, false, false);

Queues may also be deleted or purged using the DeleteQueue and PurgeQueue methods.

Binding Queues to Exchanges

The BindQueue method is used to bind a queue to an exchange. Exchanges use the information held by their queue bindings to determine which messages to forward to which queues.

Note that all AMQP 0.9.1 servers automatically bind all queues to their default exchange (which is always a direct exchange with no name) using each queue's name as the binding's routing key. This makes it easy to send a message to a specific queue without having to declare bindings; just call PublishMessage, pass empty string for ExchangeName, and the name of the desired queue for RoutingKey.

Binding a Queue to an Exchange

// Bind a queue to an exchange. Messages will only be delivered to the queue if their routing key is "MyRoutingKey".
amqpc1.BindQueue("channel", "MyQueue", "MyExchange", "MyRoutingKey", false);

Queues can also be unbound from exchanges using the UnbindQueue method.

Publishing Messages

To publish a message, populate the Message* properties, and then call the PublishMessage method.

Publishing a Message

amqpc1.Message.Body = "Hello, world!";

// Publish a message to the server's default (no-name) exchange, using the name of a specific queue as the routing key.
amqpc1.PublishMessage("channel", "", "MyQueue", false, false);

// Publish a message to the "MyExchange" exchange, using the routing key "MyRoutingKey".
amqpc1.PublishMessage("channel", "MyExchange", "MyRoutingKey", false, false);

Note that outgoing messages may be handled differently by the server if the channel they are sent over is in transaction or (for RabbitMQ only) "publish confirmations" mode. Refer to the EnableTransactionMode and EnablePublishConfirms methods for more information.

Receiving Messages

There are two possible ways for the class to receive a message:

  • Messages can be asynchronously pushed to the class from the server. At any point in time, the server may push a message to the class from a queue that the Consume method has been used to attach a consumer to.
  • Messages can be synchronously pulled from the server by the class. The FetchMessage method is used to attempt to pull (or "fetch") messages from a specific queue.

Regardless of how they are received, all incoming messages cause the ReceivedMessage* properties to be populated and the MessageIn event to fire.

Receiving a Message

// MessageIn event handler.
amqpc1.OnMessageIn += (s, e) => {
  if (e.MessageCount == -1) {
    // The server pushed a message to us asynchronously due to a consumer we created.
    Console.WriteLine("The server pushed this message to us via consumer '" + e.ConsumerTag + "':");
    Console.WriteLine(amqpc1.ReceivedMessage.Body);
  } else if (e.DeliveryTag > 0) {
    // We pulled a message from a queue with the FetchMessage() method.
    Console.WriteLine("Message successfully pulled:");
    Console.WriteLine(amqpc1.ReceivedMessage.Body);
    Console.WriteLine(e.MessageCount + " messages are still available to pull.");
  } else {
    // We tried to pull a message, but there were none available to pull.
    Console.WriteLine("No messages available to pull.");
  }
};

// Attach a consumer to "MyQueue".
amqpc1.Consume("channel", "MyQueue", "consumerTag", false, true, false, false);

// Or, try to fetch a message from "MyQueue".
amqpc1.FetchMessage("channel", "MyQueue", true);

Note that the MessageIn event always fires if FetchMessage is called successfully, even if there were no messages available to fetch; refer to MessageIn for more information.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

ArgumentCountThe number of records in the Argument arrays.
ArgumentNameThe table property's name.
ArgumentValueThe table property's value.
ArgumentValueTypeThe table property's value type.
AuthSchemeThe authentication scheme to use when connecting.
ChannelCountThe number of records in the Channel arrays.
ChannelAcceptWhether the channel is currently accepting new messages from the server.
ChannelModeWhat mode the channel is operating in.
ChannelNameThe name of the channel.
ChannelReadyToSendWhether the channel is ready to send a message.
ClientPropertyCountThe number of records in the ClientProperty arrays.
ClientPropertyNameThe table property's name.
ClientPropertyValueThe table property's value.
ClientPropertyValueTypeThe table property's value type.
ConnectedTriggers a connection or disconnection.
FirewallAutoDetectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallTypeThis property determines the type of firewall to connect through.
FirewallHostThis property contains the name or IP address of firewall (optional).
FirewallPasswordThis property contains a password if authentication is to be used when connecting through the firewall.
FirewallPortThis property contains the TCP port for the firewall Host .
FirewallUserThis property contains a user name if authentication is to be used connecting through a firewall.
HeartbeatThe heartbeat timeout value.
IncomingMessageCountThe number of records in the IncomingMessage arrays.
IncomingMessageAppIdThe Id of the application that created the message.
IncomingMessageBodyThe message body.
IncomingMessageChannelNameThe name of the channel the message is associated with.
IncomingMessageContentEncodingThe content encoding of the message's body.
IncomingMessageContentTypeThe content type (MIME type) of the message's body.
IncomingMessageCorrelationIdThe correlation Id of the message.
IncomingMessageDeliveryModeThe delivery mode of the message.
IncomingMessageExpirationThe time-to-live value for this message.
IncomingMessageHeadersHeaders associated with the message.
IncomingMessageIdThe unique Id of the message.
IncomingMessagePriorityThe priority of the message.
IncomingMessageReplyToThe address to send replies to for the message.
IncomingMessageTimestampThe message's timestamp.
IncomingMessageTypeThe message's type.
IncomingMessageUserIdThe identity of the user responsible for producing the message.
LocalHostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
LocalPortThe TCP port in the local host where the class binds.
MessageAppIdThe Id of the application that created the message.
MessageBodyThe message body.
MessageChannelNameThe name of the channel the message is associated with.
MessageContentEncodingThe content encoding of the message's body.
MessageContentTypeThe content type (MIME type) of the message's body.
MessageCorrelationIdThe correlation Id of the message.
MessageDeliveryModeThe delivery mode of the message.
MessageExpirationThe time-to-live value for this message.
MessageHeadersHeaders associated with the message.
MessageIdThe unique Id of the message.
MessagePriorityThe priority of the message.
MessageReplyToThe address to send replies to for the message.
MessageTimestampThe message's timestamp.
MessageTypeThe message's type.
MessageUserIdThe identity of the user responsible for producing the message.
OutgoingMessageCountThe number of records in the OutgoingMessage arrays.
OutgoingMessageAppIdThe Id of the application that created the message.
OutgoingMessageBodyThe message body.
OutgoingMessageChannelNameThe name of the channel the message is associated with.
OutgoingMessageContentEncodingThe content encoding of the message's body.
OutgoingMessageContentTypeThe content type (MIME type) of the message's body.
OutgoingMessageCorrelationIdThe correlation Id of the message.
OutgoingMessageDeliveryModeThe delivery mode of the message.
OutgoingMessageExpirationThe time-to-live value for this message.
OutgoingMessageHeadersHeaders associated with the message.
OutgoingMessageIdThe unique Id of the message.
OutgoingMessagePriorityThe priority of the message.
OutgoingMessageReplyToThe address to send replies to for the message.
OutgoingMessageTimestampThe message's timestamp.
OutgoingMessageTypeThe message's type.
OutgoingMessageUserIdThe identity of the user responsible for producing the message.
PasswordA password to use for SASL authentication.
QueueMessageCountThe message count returned by various queue operations.
ReceivedMessageAppIdThe Id of the application that created the message.
ReceivedMessageBodyThe message body.
ReceivedMessageChannelNameThe name of the channel the message is associated with.
ReceivedMessageContentEncodingThe content encoding of the message's body.
ReceivedMessageContentTypeThe content type (MIME type) of the message's body.
ReceivedMessageCorrelationIdThe correlation Id of the message.
ReceivedMessageDeliveryModeThe delivery mode of the message.
ReceivedMessageExpirationThe time-to-live value for this message.
ReceivedMessageHeadersHeaders associated with the message.
ReceivedMessageIdThe unique Id of the message.
ReceivedMessagePriorityThe priority of the message.
ReceivedMessageReplyToThe address to send replies to for the message.
ReceivedMessageTimestampThe message's timestamp.
ReceivedMessageTypeThe message's type.
ReceivedMessageUserIdThe identity of the user responsible for producing the message.
RemoteHostThe address of the remote host. Domain names are resolved to IP addresses.
RemotePortThe port of the AQMP server (default is 5672). The default port for SSL is 5671.
ServerPropertyCountThe number of records in the ServerProperty arrays.
ServerPropertyNameThe table property's name.
ServerPropertyValueThe table property's value.
ServerPropertyValueTypeThe table property's value type.
SSLAcceptServerCertEncodedThe certificate (PEM/base64 encoded).
SSLCertEncodedThe certificate (PEM/base64 encoded).
SSLCertStoreThe name of the certificate store for the client certificate.
SSLCertStorePasswordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
SSLCertStoreTypeThe type of certificate store for this certificate.
SSLCertSubjectThe subject of the certificate used for client authentication.
SSLEnabledWhether TLS/SSL is enabled.
SSLServerCertEncodedThe certificate (PEM/base64 encoded).
TimeoutA timeout for the class.
UserA username to use for SASL authentication.
VirtualHostThe virtual host to connect to.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

BindQueueBinds a queue to an exchange.
CancelConsumeCancels an existing consumer.
CloseChannelCloses a channel.
CommitTransactionCommits the current transaction for a channel.
ConfigSets or retrieves a configuration setting.
ConnectConnects to a remote host.
ConsumeStarts a new consumer for a given queue.
CreateChannelCreates a new channel.
DeclareExchangeVerifies that an exchange exists, potentially creating it if necessary.
DeclareQueueVerifies that a queue exists, potentially creating it if necessary.
DeleteExchangeDeletes an exchange.
DeleteQueueDeletes a queue.
DisconnectDisconnects from the remote host.
DoEventsProcesses events from the internal message queue.
EnablePublishConfirmsEnables publish confirmations mode for a channel.
EnableTransactionModeEnables transaction mode for a channel.
FetchMessageAttempts to fetch a message from a given queue.
InterruptInterrupt the current action and disconnects from the remote host.
PublishMessagePublishes a message.
PurgeQueuePurges all messages from a queue.
RecoverRequest that the server redeliver all messages on a given channel that have not been acknowledged.
ResetReset the class.
ResetMessageResets the Message properties.
RollbackTransactionRolls back the current transaction for a channel.
SetChannelAcceptDisables or enables message acceptance for a given channel.
SetQoSRequests a specific quality of service (QoS).
UnbindQueueRemoves a previously-created queue binding.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

ChannelReadyToSendFires when a channel is ready to send messages.
ConnectedFired immediately after a connection completes (or fails).
ConnectionStatusFired to indicate changes in connection state.
DisconnectedFired when a connection is closed.
ErrorInformation about errors during data delivery.
LogFires once for each log message.
MessageInFires when a message is received; as well as when an attempt is made to fetch a message from a currently empty queue.
MessageOutFires when a message is published.
MessageReturnedFires if a previously published message is returned by the server due to it being undeliverable.
SSLServerAuthenticationFired after the server presents its certificate to the client.
SSLStatusShows the progress of the secure connection.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AuthorizationIdentityThe value to use as the authorization identity when SASL authentication is used.
ConsumerTagThe consumer tag associated with the most recently created consumer.
LocaleThe desired message locale to use.
LocalesThe message locales supported by the server.
LogLevelThe level of detail that is logged.
MaxChannelCountThe maximum number of channels.
MaxFrameSizeThe maximum frame size.
MechanismsThe authentication mechanisms supported by the server.
NackMultipleWhether negative acknowledgments should be cumulative or not.
ProtocolVersionThe AMQP protocol version to conform to.
QueueConsumerCountThe consumer count associated with the most recently created (or verified) queue.
QueueNameThe queue name associated with the most recently created (or verified) queue.
RabbitMQCompatibleWhether to operate in a mode compatible with RabbitMQ.
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
OpenSSLCADirThe path to a directory containing CA certificates.
OpenSSLCAFileName of the file containing the list of CA's trusted by your application.
OpenSSLCipherListA string that controls the ciphers to be used by SSL.
OpenSSLPrngSeedDataThe data to seed the pseudo random number generator (PRNG).
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertFilePathsThe paths to CA certificate files on Unix/Linux.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedVersionReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 PHP Edition - Version 20.0 [Build 8265]