当前位置:   article > 正文

MQTT协议之订阅及发布(使用paho-mqtt-client或mqttv3实现)_paho.mqtt.cpp同时实现发布和订阅

paho.mqtt.cpp同时实现发布和订阅

另外一个MQTT发布订阅客户端paho-mqtt-client或mqttv3采用回调的方式实现消息的接收,下面看一下实现:

1.消息接收回调类

  1. package cn.smartslim.mqtt.demo.paho;
  2. import org.eclipse.paho.client.mqttv3.MqttCallback;
  3. import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
  4. import org.eclipse.paho.client.mqttv3.MqttMessage;
  5. import org.eclipse.paho.client.mqttv3.MqttTopic;
  6. /**
  7. * 发布消息的回调类
  8. *
  9. * 必须实现MqttCallback的接口并实现对应的相关接口方法
  10. * ◦CallBack 类将实现 MqttCallBack。每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。在回调中,将它用来标识已经启动了该回调的哪个实例。
  11. * ◦必须在回调类中实现三个方法:
  12. *
  13. * public void messageArrived(MqttTopic topic, MqttMessage message)
  14. * 接收已经预订的发布。
  15. *
  16. * public void connectionLost(Throwable cause)
  17. * 在断开连接时调用。
  18. *
  19. * public void deliveryComplete(MqttDeliveryToken token))
  20. * 接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。
  21. * ◦由 MqttClient.connect 激活此回调。
  22. *
  23. */
  24. public class PushCallback implements MqttCallback {
  25. public void connectionLost(Throwable cause) {
  26. // 连接丢失后,一般在这里面进行重连
  27. System.out.println("连接断开,可以做重连");
  28. }
  29. public void deliveryComplete(MqttDeliveryToken token) {
  30. // publish后会执行到这里
  31. System.out.println("deliveryComplete---------"+ token.isComplete());
  32. }
  33. public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {
  34. // subscribe后得到的消息会执行到这里面
  35. System.out.println("接收消息主题:"+topic.getName());
  36. System.out.println("接收消息Qos:"+message.getQos());
  37. System.out.println("接收消息内容:"+new String(message.getPayload()));
  38. }
  39. }
2.服务端发布消息

  1. package cn.smartslim.mqtt.demo.paho;
  2. import org.eclipse.paho.client.mqttv3.MqttClient;
  3. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  4. import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
  5. import org.eclipse.paho.client.mqttv3.MqttException;
  6. import org.eclipse.paho.client.mqttv3.MqttMessage;
  7. import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
  8. import org.eclipse.paho.client.mqttv3.MqttTopic;
  9. import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;
  10. public class Server {
  11. public static final String HOST = "tcp://192.168.36.102:1883";
  12. public static final String TOPIC = "tokudu/yzq124";
  13. private static final String clientid ="server";
  14. private MqttClient client;
  15. private MqttTopic topic;
  16. private String userName = "test";
  17. private String passWord = "test";
  18. private MqttMessage message;
  19. public Server() throws MqttException {
  20. //MemoryPersistence设置clientid的保存形式,默认为以内存保存
  21. client = new MqttClient(HOST, clientid, new MemoryPersistence());
  22. connect();
  23. }
  24. private void connect() {
  25. MqttConnectOptions options = new MqttConnectOptions();
  26. options.setCleanSession(false);
  27. options.setUserName(userName);
  28. options.setPassword(passWord.toCharArray());
  29. // 设置超时时间
  30. options.setConnectionTimeout(10);
  31. // 设置会话心跳时间
  32. options.setKeepAliveInterval(20);
  33. try {
  34. client.setCallback(new PushCallback());
  35. client.connect(options);
  36. topic = client.getTopic(TOPIC);
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. public void publish(MqttMessage message) throws MqttPersistenceException, MqttException{
  42. MqttDeliveryToken token = topic.publish(message);
  43. token.waitForCompletion();
  44. System.out.println(token.isComplete()+"========");
  45. }
  46. public static void main(String[] args) throws MqttException {
  47. Server server = new Server();
  48. server.message = new MqttMessage();
  49. server.message.setQos(1);
  50. server.message.setRetained(true);
  51. server.message.setPayload("eeeeeaaaaaawwwwww---".getBytes());
  52. server.publish(server.message);
  53. System.out.println(server.message.isRetained()+"------ratained状态");
  54. }
  55. }
3.客户端接收消息

  1. package cn.smartslim.mqtt.demo.paho;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.ScheduledExecutorService;
  4. import java.util.concurrent.TimeUnit;
  5. import org.eclipse.paho.client.mqttv3.MqttClient;
  6. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  7. import org.eclipse.paho.client.mqttv3.MqttException;
  8. import org.eclipse.paho.client.mqttv3.MqttSecurityException;
  9. import org.eclipse.paho.client.mqttv3.MqttTopic;
  10. import org.eclipse.paho.client.mqttv3.internal.MemoryPersistence;
  11. public class Client {
  12. public static final String HOST = "tcp://192.168.36.102:1883";
  13. public static final String TOPIC = "tokudu/yzq124";
  14. private static final String clientid = "client";
  15. private MqttClient client;
  16. private MqttConnectOptions options;
  17. private String userName = "test";
  18. private String passWord = "test";
  19. private ScheduledExecutorService scheduler;
  20. //重新链接
  21. public void startReconnect() {
  22. scheduler = Executors.newSingleThreadScheduledExecutor();
  23. scheduler.scheduleAtFixedRate(new Runnable() {
  24. public void run() {
  25. if (!client.isConnected()) {
  26. try {
  27. client.connect(options);
  28. } catch (MqttSecurityException e) {
  29. e.printStackTrace();
  30. } catch (MqttException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }
  35. }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
  36. }
  37. private void start() {
  38. try {
  39. // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
  40. client = new MqttClient(HOST, clientid, new MemoryPersistence());
  41. // MQTT的连接设置
  42. options = new MqttConnectOptions();
  43. // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
  44. options.setCleanSession(true);
  45. // 设置连接的用户名
  46. options.setUserName(userName);
  47. // 设置连接的密码
  48. options.setPassword(passWord.toCharArray());
  49. // 设置超时时间 单位为秒
  50. options.setConnectionTimeout(10);
  51. // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
  52. options.setKeepAliveInterval(20);
  53. // 设置回调
  54. client.setCallback(new PushCallback());
  55. MqttTopic topic = client.getTopic(TOPIC);
  56. //setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
  57. options.setWill(topic, "close".getBytes(), 0, true);
  58. client.connect(options);
  59. //订阅消息
  60. int[] Qos = {1};
  61. String[] topic1 = {TOPIC};
  62. client.subscribe(topic1, Qos);
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. public void disconnect() {
  68. try {
  69. client.disconnect();
  70. } catch (MqttException e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. public static void main(String[] args) throws MqttException {
  75. Client client = new Client();
  76. client.start();
  77. }
  78. }

Android手机客户端实现demo:

https://github.com/dobermai/android-mqtt-push


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/188596
推荐阅读
相关标签
  

闽ICP备14008679号