客户端和服务端

http://blog.csdn.net/zhu_tianwei/article/details/42983689

2015

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

1.消息接收回调类

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

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

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

Android手机客户端实现demo:

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

猜你喜欢

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