MQTT
发送消息
首先创建一个MqttClient对象用于连接到远程的MQTT服务器,第一个参数为地址,第二个参数为客户端名称,第三个参数为clientid保存形式。
然后可以创建一个主题叫做MQTT Example
Qos为服务质量级别:Qos = 0至多一次;
Qos = 1至少一次;
Qos = 2刚好一次;
这时候就可以开始连接了
调用topic的publish方法将消息发送给服务器端,MqttDeliveryToken返回可以得知是否完成。
MqttClient client = new MqttClient("tcp://9.119.154.32:1883","java_client", null);
MqttTopic topic = client.getTopic("MQTT Example");
MqttMessage message = new MqttMessage("Hello World. Hello IBM".getBytes());
message.setQos(1);
client.connect();
MqttDeliveryToken token = topic.publish(message);
接收消息
先写一个Callback类继承MqttCallback,需要实现messageArrived()、connectionLost()和deliveryComplete()三个方法以响应不同的事件。
messageArrived()方法负责响应收到消息后的事件。将消息内容放到bundle中通过handler将message发送给主线程。
public class CallBack implements MqttCallback {
private String instanceDatahttps://www.it610.com/article/= "";
private Handler handler;
public CallBack(String instance, Handler handler) {
instanceData = https://www.it610.com/article/instance;
this.handler = handler;
}
public void messageArrived(MqttTopic topic, MqttMessage message) {
try {
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("content", message.toString());
msg.setData(bundle);
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public void connectionLost(Throwable cause) {}
public void deliveryComplete(MqttDeliveryToken token) {}
}
然后我们构造一个参数为handler的方法
创建一个client对象
实现callback对象
设置callback
Subscribe()方法为订阅主题字符串为“QTT Example”的消息
MqttClient client = new MqttClient("tcp://9.119.154.32:1883", "java_client", null);
CallBack callback = new CallBack("java_client", handler);
client.setCallback(callback);
MqttConnectOptions conOptions = new MqttConnectOptions();
conOptions.setCleanSession(false);
client.connect(conOptions);
client.subscribe("MQTT Example", 1);
Thread.sleep(10000);
client.disconnect();
【如何写一个MQTT连接的android客户端】最后在主线程中调用参数为handler的这个方法,接收到Callback通过handler对象发来的消息。