-
- All Implemented Interfaces:
-
org.eclipse.paho.client.mqttv3.IMqttClient
public class MqttClient implements IMqttClient
Lightweight client for talking to an MQTT server using methods that block until an operation completes.
This class implements the blocking IMqttClient client interface where all actions block until they have completed (or timed out). This implementation is compatible with all Java SE runtimes from 1.4.2 and up.
An application can connect to an MQTT server using:
- A plain TCP socket
- An secure SSL/TLS socket
To enable messages to be delivered even across network and client restarts messages need to be safely stored until the message has been delivered at the requested quality of service. A pluggable persistence mechanism is provided to store the messages.
By default MqttDefaultFilePersistence is used to store messages to a file. If persistence is set to null then messages are stored in memory and hence can be lost if the client, Java runtime or device shuts down.
If connecting with setCleanSession set to true it is safe to use memory persistence as all state it cleared when a client disconnects. If connecting with cleanSession set to false, to provide reliable message delivery then a persistent message store should be used such as the default one.
The message store interface is pluggable. Different stores can be used by implementing the MqttClientPersistence interface and passing it to the clients constructor.
-
-
Field Summary
Fields Modifier and Type Field Description protected longtimeToWait
-
Constructor Summary
Constructors Constructor Description MqttClient(String serverURI, String clientId)Create an MqttClient that can be used to communicate with an MQTT server. MqttClient(String serverURI, String clientId, MqttClientPersistence persistence)Create an MqttClient that can be used to communicate with an MQTT server.
-
Method Summary
Modifier and Type Method Description longgetTimeToWait()Return the maximum time to wait for an action to complete. voidsetTimeToWait(long timeToWaitInMillis)Set the maximum time to wait for an action to complete. voidconnect()Connects to an MQTT server using the default options. voidconnect(MqttConnectOptions options)Connects to an MQTT server using the specified options. voiddisconnect()Disconnects from the server. voiddisconnect(long quiesceTimeout)Disconnects from the server. voiddisconnectForcibly()Disconnects from the server forcibly to reset all the states. voiddisconnectForcibly(long disconnectTimeout)Disconnects from the server forcibly to reset all the states. voiddisconnectForcibly(long quiesceTimeout, long disconnectTimeout)Disconnects from the server forcibly to reset all the states. voidsubscribe(String topicFilter)Subscribe to a topic, which may include wildcards using a QoS of 1. voidsubscribe(Array<String> topicFilters)Subscribes to a one or more topics, which may include wildcards using a QoS of 1. voidsubscribe(String topicFilter, int qos)Subscribe to a topic, which may include wildcards. voidsubscribe(Array<String> topicFilters, Array<int> qos)Subscribes to multiple topics, each of which may include wildcards. voidunsubscribe(String topicFilter)Requests the server unsubscribe the client from a topic. voidunsubscribe(Array<String> topicFilters)Requests the server unsubscribe the client from one or more topics. voidpublish(String topic, Array<byte> payload, int qos, boolean retained)Publishes a message to a topic on the server and return once it is delivered. voidpublish(String topic, MqttMessage message)Publishes a message to a topic on the server. voidclose()Close the client Releases all resource associated with the client. StringgetClientId()Returns the client ID used by this client. Array<IMqttDeliveryToken>getPendingDeliveryTokens()Returns the delivery tokens for any outstanding publish operations. StringgetServerURI()Returns the address of the server used by this client, as a URI. MqttTopicgetTopic(String topic)Get a topic object which can be used to publish messages. booleanisConnected()Determines if this client is currently connected to the server. voidsetCallback(MqttCallback callback)Sets the callback listener to use for events that happen asynchronously. static StringgenerateClientId()Returns a randomly generated client identifier based on the current user's login name and the system time. -
-
Constructor Detail
-
MqttClient
MqttClient(String serverURI, String clientId)
Create an MqttClient that can be used to communicate with an MQTT server.- Parameters:
serverURI- the address of the server to connect to, specified as a URI.clientId- a client identifier that is unique on the server being connected to
-
MqttClient
MqttClient(String serverURI, String clientId, MqttClientPersistence persistence)
Create an MqttClient that can be used to communicate with an MQTT server.- Parameters:
serverURI- the address of the server to connect to, specified as a URI.clientId- a client identifier that is unique on the server being connected topersistence- the persistence class to use to store in-flight message.
-
-
Method Detail
-
getTimeToWait
long getTimeToWait()
Return the maximum time to wait for an action to complete.
-
setTimeToWait
void setTimeToWait(long timeToWaitInMillis)
Set the maximum time to wait for an action to complete.
Set the maximum time to wait for an action to complete before returning control to the invoking application. Control is returned when:
- the action completes
- or when the timeout if exceeded
- or when the client is disconnect/shutdown
- Parameters:
timeToWaitInMillis- before the action times out.
-
connect
void connect()
Connects to an MQTT server using the default options.
The default options are specified in MqttConnectOptions class.
-
connect
void connect(MqttConnectOptions options)
Connects to an MQTT server using the specified options.
The server to connect to is specified on the constructor. It is recommended to call setCallback prior to connecting in order that messages destined for the client can be accepted as soon as the client is connected.
This is a blocking method that returns once connect completes
- Parameters:
options- a set of connection parameters that override the defaults.
-
disconnect
void disconnect()
Disconnects from the server.
An attempt is made to quiesce the client allowing outstanding work to complete before disconnecting. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting. This method must not be called from inside MqttCallback methods.
-
disconnect
void disconnect(long quiesceTimeout)
Disconnects from the server.
The client will wait for all MqttCallback methods to complete. It will then wait for up to the quiesce timeout to allow for work which has already been initiated to complete - for example, it will wait for the QoS 2 flows from earlier publications to complete. When work has completed or after the quiesce timeout, the client will disconnect from the server. If the cleanSession flag was set to false and is set to false the next time a connection is made QoS 1 and 2 messages that were not previously delivered will be delivered.
This is a blocking method that returns once disconnect completes
- Parameters:
quiesceTimeout- the amount of time in milliseconds to allow for existing work to finish before disconnecting.
-
disconnectForcibly
void disconnectForcibly()
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting and wait for a maximum of 10 seconds for sending the disconnect packet to server.
-
disconnectForcibly
void disconnectForcibly(long disconnectTimeout)
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting.
- Parameters:
disconnectTimeout- the amount of time in milliseconds to allow send disconnect packet to server.
-
disconnectForcibly
void disconnectForcibly(long quiesceTimeout, long disconnectTimeout)
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet.
- Parameters:
quiesceTimeout- the amount of time in milliseconds to allow for existing work to finish before disconnecting.disconnectTimeout- the amount of time in milliseconds to allow send disconnect packet to server.
-
subscribe
void subscribe(String topicFilter)
Subscribe to a topic, which may include wildcards using a QoS of 1.
- Parameters:
topicFilter- the topic to subscribe to, which can include wildcards.
-
subscribe
void subscribe(Array<String> topicFilters)
Subscribes to a one or more topics, which may include wildcards using a QoS of 1.
- Parameters:
topicFilters- the topic to subscribe to, which can include wildcards.
-
subscribe
void subscribe(String topicFilter, int qos)
Subscribe to a topic, which may include wildcards.
- Parameters:
topicFilter- the topic to subscribe to, which can include wildcards.qos- the maximum quality of service at which to subscribe.
-
subscribe
void subscribe(Array<String> topicFilters, Array<int> qos)
Subscribes to multiple topics, each of which may include wildcards.
The setCallback method should be called before this method, otherwise any received messages will be discarded.
If (@link MqttConnectOptions#setCleanSession(boolean)} was set to true when when connecting to the server then the subscription remains in place until either:
- The client disconnects
- An unsubscribe method is called to un-subscribe the topic
If (@link MqttConnectOptions#setCleanSession(boolean)} was set to false when when connecting to the server then the subscription remains in place until either:
The "topic filter" string used when subscribing may contain special characters, which allow you to subscribe to multiple topics at once.
The topic level separator is used to introduce structure into the topic, and can therefore be specified within the topic for that purpose. The multi-level wildcard and single-level wildcard can be used for subscriptions, but they cannot be used within a topic by the publisher of a message.
This is a blocking method that returns once subscribe completes
- Parameters:
topicFilters- one or more topics to subscribe to, which can include wildcards.qos- the maximum quality of service to subscribe each topic at.Messages published at a lower quality of service will be received at the published QoS.
-
unsubscribe
void unsubscribe(String topicFilter)
Requests the server unsubscribe the client from a topic.
- Parameters:
topicFilter- the topic to unsubscribe from.
-
unsubscribe
void unsubscribe(Array<String> topicFilters)
Requests the server unsubscribe the client from one or more topics.
Unsubcribing is the opposite of subscribing. When the server receives the unsubscribe request it looks to see if it can find a subscription for the client and then removes it. After this point the server will send no more messages to the client for this subscription.
The topic(s) specified on the unsubscribe must match the topic(s) specified in the original subscribe request for the subscribe to succeed
This is a blocking method that returns once unsubscribe completes
- Parameters:
topicFilters- one or more topics to unsubscribe from.
-
publish
void publish(String topic, Array<byte> payload, int qos, boolean retained)
Publishes a message to a topic on the server and return once it is delivered.
This is a convenience method, which will create a new MqttMessage object with a byte array payload and the specified QoS, and then publish it. All other values in the message will be set to the defaults.
- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".payload- the byte array to use as the payloadqos- the Quality of Service to deliver the message at.retained- whether or not this message should be retained by the server.
-
publish
void publish(String topic, MqttMessage message)
Publishes a message to a topic on the server.
Delivers a message to the server at the requested quality of service and returns control once the message has been delivered. In the event the connection fails or the client stops, any messages that are in the process of being delivered will be delivered once a connection is re-established to the server on condition that:
- The connection is re-established with the same clientID
- The original connection was made with (@link MqttConnectOptions#setCleanSession(boolean)} set to false
- The connection is re-established with (@link MqttConnectOptions#setCleanSession(boolean)} set to false
In the event that the connection breaks or the client stops it is still possible to determine when the delivery of the message completes. Prior to re-establishing the connection to the server:
- Register a setCallback callback on the client and the delivery complete callback will be notified once a delivery of a message completes
- or call getPendingDeliveryTokens which will return a token for each message that is in-flight. The token can be used to wait for delivery to complete.
When building an application, the design of the topic tree should take into account the following principles of topic name syntax and semantics:
- A topic must be at least one character long.
- Topic names are case sensitive. For example, ACCOUNTS and Accounts are two different topics.
- Topic names can include the space character. For example, Accounts payable is a valid topic.
- A leading "/" creates a distinct topic. For example, /finance is different from finance. /finance matches "+/+" and "/+", but not "+".
- Do not include the null character (Unicode\x0000) in any topic.
The following principles apply to the construction and content of a topic tree:
- The length is limited to 64k but within that there are no limits to the number of levels in a topic tree.
- There can be any number of root nodes; that is, there can be any number of topic trees.
This is a blocking method that returns once publish completes
*- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".message- to delivery to the server
-
close
void close()
Close the client Releases all resource associated with the client. After the client has been closed it cannot be reused. For instance attempts to connect will fail.
-
getClientId
String getClientId()
Returns the client ID used by this client.
All clients connected to the same server or server farm must have a unique ID.
-
getPendingDeliveryTokens
Array<IMqttDeliveryToken> getPendingDeliveryTokens()
Returns the delivery tokens for any outstanding publish operations.
If a client has been restarted and there are messages that were in the process of being delivered when the client stopped this method will return a token for each message enabling the delivery to be tracked Alternately the deliveryComplete callback can be used to track the delivery of outstanding messages.
If a client connects with cleanSession true then there will be no delivery tokens as the cleanSession option deletes all earlier state. For state to be remembered the client must connect with cleanSession set to false
-
getServerURI
String getServerURI()
Returns the address of the server used by this client, as a URI.
The format is the same as specified on the constructor.
-
getTopic
MqttTopic getTopic(String topic)
Get a topic object which can be used to publish messages.
An alternative method that should be used in preference to this one when publishing a message is:
- publish to publish a message in a blocking manner
- or use publish methods on the non-blocking client like publish
When building an application, the design of the topic tree should take into account the following principles of topic name syntax and semantics:
- A topic must be at least one character long.
- Topic names are case sensitive. For example, ACCOUNTS and Accounts are two different topics.
- Topic names can include the space character. For example, Accounts payable is a valid topic.
- A leading "/" creates a distinct topic. For example, /finance is different from finance. /finance matches "+/+" and "/+", but not "+".
- Do not include the null character (Unicode\x0000) in any topic.
The following principles apply to the construction and content of a topic tree:
- The length is limited to 64k but within that there are no limits to the number of levels in a topic tree.
- There can be any number of root nodes; that is, there can be any number of topic trees.
- Parameters:
topic- the topic to use, for example "finance/stock/ibm".
-
isConnected
boolean isConnected()
Determines if this client is currently connected to the server.
-
setCallback
void setCallback(MqttCallback callback)
Sets the callback listener to use for events that happen asynchronously.
There are a number of events that listener will be notified about. These include
- A new message has arrived and is ready to be processed
- The connection to the server has been lost
- Delivery of a message to the server has completed.
Other events that track the progress of an individual operation such as connect and subscribe can be tracked using the MqttToken passed to the operation
- Parameters:
callback- the class to callback when for events related to the client
-
generateClientId
static String generateClientId()
Returns a randomly generated client identifier based on the current user's login name and the system time.
When cleanSession is set to false, an application must ensure it uses the same client identifier when it reconnects to the server to resume state and maintain assured message delivery.
-
-
-
-