MQTT客户端--基于paho实现(Java)


订阅类:

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

发布类:

  1. /**
  2. * @Title: Server.java
  3. * @Package org.chisj.mqtt
  4. * @Description: TODO
  5. * @author chisj [email protected]
  6. * @date 2017年4月1日
  7. */
  8. package org.chisj.mqtt;
  9. import org.eclipse.paho.client.mqttv3.MqttClient;
  10. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  11. import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
  12. import org.eclipse.paho.client.mqttv3.MqttException;
  13. import org.eclipse.paho.client.mqttv3.MqttMessage;
  14. import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
  15. import org.eclipse.paho.client.mqttv3.MqttTopic;
  16. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  17. /**
  18. * ClassName: Server
  19. * @Description: TODO
  20. * @author chisj [email protected]
  21. * @date 2017年4月1日
  22. */
  23. public class Server {
  24. //public static final String HOST = "tcp://0.0.0.0:61613";tcp://192.168.1.100:1883
  25. public static final String HOST = "tcp://192.168.1.100:1883";
  26. public static final String TOPIC = "webServer";
  27. public static final String TOPIC125 = "toclient/125";
  28. private static final String clientid = "server";
  29. private MqttClient client;
  30. private MqttTopic topic;
  31. private MqttTopic topic125;
  32. private String userName = "admin";
  33. private String passWord = "password";
  34. private MqttMessage message;
  35. public Server() throws MqttException {
  36. // MemoryPersistence设置clientid的保存形式,默认为以内存保存
  37. client = new MqttClient(HOST, clientid, new MemoryPersistence());
  38. connect();
  39. }
  40. private void connect() {
  41. MqttConnectOptions options = new MqttConnectOptions();
  42. options.setCleanSession( false);
  43. options.setUserName(userName);
  44. options.setPassword(passWord.toCharArray());
  45. // 设置超时时间
  46. options.setConnectionTimeout( 10);
  47. // 设置会话心跳时间
  48. options.setKeepAliveInterval( 20);
  49. try {
  50. client.setCallback( new PushCallback());
  51. client.connect(options);
  52. topic = client.getTopic(TOPIC);
  53. topic125 = client.getTopic(TOPIC125);
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
  59. MqttException {
  60. MqttDeliveryToken token = topic.publish(message);
  61. token.waitForCompletion();
  62. System.out.println( "message is published completely! "
  63. + token.isComplete());
  64. }
  65. public static void main(String[] args) throws MqttException {
  66. Server server = new Server();
  67. server.message = new MqttMessage();
  68. server.message.setQos( 2);
  69. server.message.setRetained( true);
  70. server.message.setPayload( "给客户端124推送的信息".getBytes());
  71. server.publish(server.topic , server.message);
  72. server.message = new MqttMessage();
  73. server.message.setQos(2);
  74. server.message.setRetained(true);
  75. server.message.setPayload("给客户端125推送的信息".getBytes());
  76. server.publish(server.topic125 , server.message);
  77. System.out.println(server.message.isRetained() + "------ratained状态");
  78. }
  79. }

回调类:

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



订阅类:

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

发布类:

  1. /**
  2. * @Title: Server.java
  3. * @Package org.chisj.mqtt
  4. * @Description: TODO
  5. * @author chisj [email protected]
  6. * @date 2017年4月1日
  7. */
  8. package org.chisj.mqtt;
  9. import org.eclipse.paho.client.mqttv3.MqttClient;
  10. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  11. import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
  12. import org.eclipse.paho.client.mqttv3.MqttException;
  13. import org.eclipse.paho.client.mqttv3.MqttMessage;
  14. import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
  15. import org.eclipse.paho.client.mqttv3.MqttTopic;
  16. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  17. /**
  18. * ClassName: Server
  19. * @Description: TODO
  20. * @author chisj [email protected]
  21. * @date 2017年4月1日
  22. */
  23. public class Server {
  24. //public static final String HOST = "tcp://0.0.0.0:61613";tcp://192.168.1.100:1883
  25. public static final String HOST = "tcp://192.168.1.100:1883";
  26. public static final String TOPIC = "webServer";
  27. public static final String TOPIC125 = "toclient/125";
  28. private static final String clientid = "server";
  29. private MqttClient client;
  30. private MqttTopic topic;
  31. private MqttTopic topic125;
  32. private String userName = "admin";
  33. private String passWord = "password";
  34. private MqttMessage message;
  35. public Server() throws MqttException {
  36. // MemoryPersistence设置clientid的保存形式,默认为以内存保存
  37. client = new MqttClient(HOST, clientid, new MemoryPersistence());
  38. connect();
  39. }
  40. private void connect() {
  41. MqttConnectOptions options = new MqttConnectOptions();
  42. options.setCleanSession( false);
  43. options.setUserName(userName);
  44. options.setPassword(passWord.toCharArray());
  45. // 设置超时时间
  46. options.setConnectionTimeout( 10);
  47. // 设置会话心跳时间
  48. options.setKeepAliveInterval( 20);
  49. try {
  50. client.setCallback( new PushCallback());
  51. client.connect(options);
  52. topic = client.getTopic(TOPIC);
  53. topic125 = client.getTopic(TOPIC125);
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
  59. MqttException {
  60. MqttDeliveryToken token = topic.publish(message);
  61. token.waitForCompletion();
  62. System.out.println( "message is published completely! "
  63. + token.isComplete());
  64. }
  65. public static void main(String[] args) throws MqttException {
  66. Server server = new Server();
  67. server.message = new MqttMessage();
  68. server.message.setQos( 2);
  69. server.message.setRetained( true);
  70. server.message.setPayload( "给客户端124推送的信息".getBytes());
  71. server.publish(server.topic , server.message);
  72. server.message = new MqttMessage();
  73. server.message.setQos(2);
  74. server.message.setRetained(true);
  75. server.message.setPayload("给客户端125推送的信息".getBytes());
  76. server.publish(server.topic125 , server.message);
  77. System.out.println(server.message.isRetained() + "------ratained状态");
  78. }
  79. }

回调类:

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



猜你喜欢

转载自blog.csdn.net/wangshuminjava/article/details/80907653