mqtt 协议版本: 3.1.1
eclipse paho client 版本: 1.2.0
eclipse paho client 介绍
Paho Java Client 是一个用Java编写的MQTT客户端库, 用于开发在JVM或其他Java兼容平台(如Android)上运行的应用程序.
Paho Java Client提供了两个API: MqttAsyncClient 提供完全异步的API, 通过注册的回调完成. MqttClient 是 MqttAsyncClient 的同步包装器.
例子
String topic = "MQTT Examples";String content = "Message from MqttPublishSample";int qos = 2;String broker = "tcp://iot.eclipse.org:1883";String clientId = "JavaSample";MemoryPersistence persistence = new MemoryPersistence();try {MqttClient sampleClient = new MqttClient(broker, clientId, persistence);MqttConnectOptions connOpts = new MqttConnectOptions();connOpts.setCleanSession(true);System.out.println("Connecting to broker: "+broker);sampleClient.connect(connOpts);System.out.println("Connected");System.out.println("Publishing message: "+content);MqttMessage message = new MqttMessage(content.getBytes());message.setQos(qos);sampleClient.publish(topic, message);System.out.println("Message published");sampleClient.disconnect();System.out.println("Disconnected");System.exit(0);} catch(MqttException me) {System.out.println("reason "+me.getReasonCode());System.out.println("msg "+me.getMessage());System.out.println("loc "+me.getLocalizedMessage());System.out.println("cause "+me.getCause());System.out.println("excep "+me);me.printStackTrace();}
这个就是官网提供的例子, 可以直接连上代理做测试的.
相关类介绍
MqttClient
此类主要用于连接代理、发布消息、订阅消息、断开连接.
public void publish(String topic, byte[] payload,int qos, boolean retained) throws MqttException, MqttPersistenceException {}
public void publish(String topic, MqttMessage message) throws MqttException, MqttPersistenceException {}public void subscribe(String topicFilter) throws MqttException {}
public void subscribe(String[] topicFilters) throws MqttException {}
public void subscribe(String topicFilter, int qos) throws MqttException {}
public void subscribe(String[] topicFilters, int[] qos) throws MqttException {}
public void subscribe(String topicFilter, IMqttMessageListener messageListener) throws MqttException {}
public void subscribe(String[] topicFilters, IMqttMessageListener[] messageListeners) throws MqttException {}
public void subscribe(String topicFilter, int qos, IMqttMessageListener messageListener) throws MqttException {}
public void subscribe(String[] topicFilters, int[] qos, IMqttMessageListener[] messageListeners) throws MqttException {}public void connect() throws MqttSecurityException, MqttException {}
public void connect(MqttConnectOptions options) throws MqttSecurityException, MqttException {}public void disconnect() throws MqttException {}
public void disconnect(long quiesceTimeout) throws MqttException {}
MqttConnectOptions
此类保存了客户端连接到代理时的一些参数.
public void setUserName(String userName) {}public void setPassword(char[] password) {}public void setConnectionTimeout(int connectionTimeout) {}
MqttMessage
要发送的消息正文, 指定消息内容、Qos、Retained.
public void setQos(int qos) {}
public void setPayload(byte[] payload) {}
public void setRetained(boolean retained) {}