java写一个Mqtt协议实现收发数据

首先我用的是IDEA的maven管理去下的MQttfx的jar包

    <dependencies>
<dependency>
    <groupId>com.baidubce</groupId>
    <artifactId>bce-java-sdk</artifactId>
    <version>0.10.78</version>
</dependency>
    </dependencies>

不过我这个下的贼难受,因为下了好多好多,最后我用到的好像只有这几个


import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public  class MqttfxClient implements Runnable {

        private static   String Host="tcp://zrd6q7g.mqtt.iot.gz.baidubce.com:1883";
        private static   String username="zrd6q7g/zhang";
        private static   String password="RsG907Kzn2I3jL8s";
        private static   String clientId="hnglajh1";
        private static   int qos=1;
        private static   String topic ="point";
        private static   String content="Hello你好";
        static MqttClient client=null;

    public static void main(String[] args)throws MqttException {
        MqttfxClient mqttfxClient=new MqttfxClient();
      	 publish();
		subscribe();

    }



    public static void publish() throws MqttException{

         client =new MqttClient(Host,clientId);
        MqttConnectOptions connectOptions=new MqttConnectOptions();
        connectOptions.setCleanSession(false);
        connectOptions.setUserName(username);
        connectOptions.setPassword(password.toCharArray());
        client.connect(connectOptions);
        MqttMessage message=new MqttMessage(content.getBytes());
        message.setQos(qos);
        client.publish(topic,message);
        client.disconnect();
        client.close();
    }
    public static String subscribe() throws MqttException{
        MemoryPersistence persistence=new MemoryPersistence();
         client=new MqttClient(Host,"13tw188831",persistence);
        MqttConnectOptions connectOptions=new MqttConnectOptions();
        connectOptions.setCleanSession(false);
        connectOptions.setUserName(username);
        connectOptions.setPassword(password.toCharArray());
        client.connect(connectOptions);
        client.setCallback(new MqttCallback() {
            public void connectionLost(Throwable throwable) {

            }

            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println(mqttMessage.toString());
            }

            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("发送成功");
            }
        });
        client.subscribe("point",1);
       client.disconnect();
        client.close();
        return null;
    }
}

不过这里目前接收数据只能接收一次,因为我没有开启一个子线程让它一直接收,发送数据就是一启动就会发送一次数据。
过几天再更新一直接收数据,后期还要把接收的数据格式化。

你可能感兴趣的:(android)