/gmqyttf-client

Implementation of the client part of the MQTT protocol, MQTT协议客户端部分的实现

Primary LanguageJavaApache License 2.0Apache-2.0

Implementation of the client part of the MQTT protocol

License Forks Starts Issues

English | 中文

Get Started

  1. Dependency

    • Maven

      Add Jcenter repository first

      <repository>
          <id>jcenter</id>
          <name>jcenter</name>
          <url>https://jcenter.bintray.com</url>
      </repository>

      then

      <dependency>
          <groupId>com.dreamgyf.mqtt</groupId>
          <artifactId>gmqyttf-client</artifactId>
          <version>0.1.0</version>
          <type>pom</type>
      </dependency>
    • Gradle

      Add Jcenter repository first

      repositories {
        jcenter()
      }

      then

      implementation 'com.dreamgyf.mqtt:gmqyttf-client:0.1.0'
  2. Run

    //Build client first
    MqttClient client = new MqttClient.Builder()
       .cleanSession(true)
       .clientId("test1")
       .usernameFlag(true)
       .passwordFlag(true)
       .username("dreamgyf")
       .password("dreamgyf")
       .keepAliveTime((short) 10)
       .willFlag(true)
       .willQoS(2)
       .willTopic("/willTopic")
       .willMessage("")
       .willRetain(true)
       .build(MqttVersion.V3_1_1);
    
    //Set callback
    client.setCallback(new MqttClientCallback() {
        @Override
        public void onConnectSuccess() {
            System.out.println("Connection success");
        }
    
        @Override
        public void onConnectionException(MqttException e) {
            e.printStackTrace();
            System.err.println("Connection exception: " + e + " " + e.getMessage());
        }
    
        @Override
        public void onSubscribeFailure(MqttTopic mqttTopic) {
            System.err.println("Subscription failed: " + mqttTopic.getTopic() + " QoS: " + mqttTopic.getQoS());
        }
    
        @Override
        public void onMessageReceived(String topic, String message) {
            System.out.println("Message received, topic: " + topic + " message: " + message);
        }
    });
    
    //Connect,subscribe,publish
    client.connect("broker.emqx.io", 1883);
    
    client.subscribe(new MqttTopic("/dreamgyf/test", 2));
    client.publish("/dreamgyf/test", "publish test", new MqttPublishOption().QoS(2));