| | |
| | | package com.boying.controller.car; |
| | | |
| | | import com.google.gson.Gson; |
| | | import org.eclipse.paho.client.mqttv3.*; |
| | | import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; |
| | | |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | import java.util.Objects; |
| | | |
| | | /** |
| | | * @author kdq |
| | |
| | | public static void main(String[] args) throws MqttException { |
| | | ServerMQTT server = new ServerMQTT(); |
| | | |
| | | Map<String, Object> map2 = new HashMap<>(); |
| | | |
| | | |
| | | Map<String, Object> map = new HashMap<>(); |
| | | map.put("t",System.currentTimeMillis()); |
| | | map.put("f","control"); |
| | | map.put("d","JYGL-MTXX"); |
| | | map.put("s","0001"); |
| | | Gson gson =new Gson(); |
| | | String str = gson.toJson(map); |
| | | server.message = new MqttMessage(); |
| | | server.message.setQos(2); |
| | | server.message.setRetained(true); |
| | | server.message.setPayload("ServerMQTT".getBytes()); |
| | | server.message.setPayload(str.getBytes()); |
| | | server.publish(server.topic , server.message); |
| | | System.out.println(server.message.isRetained() + "------ratained状态"); |
| | | System.out.println("message的保留状态为:"+server.message.isRetained() + "------ratained状态"); |
| | | } |
| | | |
| | | //MQTT安装的服务器地址和端口号 |
| | | public static final String HOST = "tcp://39.96.92.240:9092"; |
| | | public static final String HOST = "tcp://47.92.115.108:1883"; |
| | | //定义一个主题 |
| | | public static final String TOPIC = "/device/message/up/ivs_result"; |
| | | public static final String TOPIC = "/MXXT"; |
| | | //定义MQTT的ID,可以在MQTT服务配置中指定 |
| | | private static final String clientid = "client-1"; |
| | | private static final String clientid = "jzadmin"+System.currentTimeMillis(); |
| | | |
| | | private MqttClient client; |
| | | private MqttTopic topic; |
| | | private String userName = "mqtt"; |
| | | private String passWord = "mqtt"; |
| | | private String userName = "jzadmin"; |
| | | private String passWord = "Sys123456"; |
| | | private MqttMessage message; |
| | | |
| | | /** |
| | |
| | | } |
| | | @Override |
| | | public void deliveryComplete(IMqttDeliveryToken token) { |
| | | System.out.println("deliveryComplete---------" + token.isComplete()); |
| | | System.out.println("mqtt的deliveryComplete回调状态为---------" + token.isComplete()); |
| | | } |
| | | @Override |
| | | public void messageArrived(String topic, MqttMessage message) throws Exception { |
| | |
| | | * t推送消息 |
| | | */ |
| | | public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException, MqttException { |
| | | topic = client.getTopic(TOPIC); |
| | | MqttDeliveryToken token = topic.publish(message); |
| | | token.waitForCompletion(); |
| | | System.out.println("message is published completely! " + token.isComplete()); |
| | | System.out.println("message 成功发送! token.isComplete状态为:" + token.isComplete()); |
| | | } |
| | | } |