io.vertx.mqtt.MqttClient Java Examples

The following examples show how to use io.vertx.mqtt.MqttClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertxMqttServerProviderTest.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@Test
void testUnSub() {
    MqttClient client = MqttClient.create(vertx);
    client.connect(1811, "127.0.0.1", result -> {
        if (!result.succeeded()) {
            result.cause().printStackTrace();
        } else {
            client.unsubscribe("/test");
        }
    });

    mqttServer
            .handleConnection()
            .flatMap(conn -> {
                Flux<MqttUnSubscription> publishingFlux = conn.handleUnSubscribe(true);
                conn.accept();
                return publishingFlux;
            })
            .flatMapIterable(pub -> pub.getMessage().topics())
            .take(1)
            .as(StepVerifier::create)
            .expectNext("/test")
            .verifyComplete();
}
 
Example #2
Source File: MqttClientIdTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void afterConnectClientIdGenerated(TestContext context) throws InterruptedException {

  Async async = context.async();

  MqttClientOptions options = new MqttClientOptions();
  MqttClient client = MqttClient.create(Vertx.vertx(), options);

  assertThat(options.getClientId(), nullValue());

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());
    assertTrue(client.clientId().length() == 36);
    assertThat(client.clientId(), notNullValue());
    assertFalse(client.clientId().isEmpty());

    log.info("Client connected with generated client id = " + client.clientId());

    async.countDown();
  });
  async.await();
}
 
Example #3
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void tcpConnectionFails(TestContext context) {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx());

  client.closeHandler(v -> {
    // when TCP connection fails, this handler should not be called, connection not established
    context.fail();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {
    // connection
    assertTrue(c.failed());
    assertFalse(client.isConnected());
    async.complete();
  });

  async.await();
}
 
Example #4
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void closeHandler(TestContext context) throws InterruptedException {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx(),
    new MqttClientOptions()
      .setKeepAliveTimeSeconds(5)
      .setAutoKeepAlive(false)
  );

  client.closeHandler((v) -> {
    async.countDown();
  });

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
  });

  async.await();
}
 
Example #5
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void connectDisconnectWithIdleOption(TestContext context) {
  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setKeepAliveTimeSeconds(100);
  MqttClient client = MqttClient.create(Vertx.vertx(),options);

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());

    client
      .disconnect(ar -> {
        assertTrue(ar.succeeded());
        async.countDown();
      });
  });

  async.await();
}
 
Example #6
Source File: MqttTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a connection to the MQTT adapter using given credentials.
 *
 * @param username The username to use for authentication.
 * @param password The password to use for authentication.
 * @return A future that will be completed with the CONNACK packet received
 *         from the adapter or failed with a {@link MqttConnectionException}
 *         if the connection could not be established.
 */
protected final Future<MqttConnAckMessage> connectToAdapter(
        final String username,
        final String password) {

    final Promise<MqttConnAckMessage> result = Promise.promise();
    VERTX.runOnContext(connect -> {
        final MqttClientOptions options = new MqttClientOptions()
                .setUsername(username)
                .setPassword(password);
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTT_PORT, IntegrationTestSupport.MQTT_HOST, result);
    });
    return result.future().map(conAck -> {
        LOGGER.debug(
                "MQTT connection to adapter [host: {}, port: {}] established",
                IntegrationTestSupport.MQTT_HOST, IntegrationTestSupport.MQTT_PORT);
        this.context = Vertx.currentContext();
        return conAck;
    });
}
 
Example #7
Source File: MqttTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Opens a connection to the MQTT adapter using an X.509 client certificate.
 *
 * @param cert The client certificate to use for authentication.
 * @return A future that will be completed with the CONNACK packet received
 *         from the adapter or failed with a {@link MqttConnectionException}
 *         if the connection could not be established.
 */
protected final Future<MqttConnAckMessage> connectToAdapter(
        final SelfSignedCertificate cert) {

    final Promise<MqttConnAckMessage> result = Promise.promise();
    VERTX.runOnContext(connect -> {
        final MqttClientOptions options = new MqttClientOptions()
                .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
                .setKeyCertOptions(cert.keyCertOptions())
                .setSsl(true);
        options.setHostnameVerificationAlgorithm("");
        mqttClient = MqttClient.create(VERTX, options);
        mqttClient.connect(IntegrationTestSupport.MQTTS_PORT, IntegrationTestSupport.MQTT_HOST, result);
    });
    return result.future().map(conAck -> {
        LOGGER.debug(
                "MQTTS connection to adapter [host: {}, port: {}] established",
                IntegrationTestSupport.MQTT_HOST, IntegrationTestSupport.MQTTS_PORT);
        this.context = Vertx.currentContext();
        return conAck;
    });
}
 
Example #8
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void connectDisconnect(TestContext context) throws InterruptedException {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx());

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());

    client
      .disconnect(ar -> {
        assertTrue(ar.succeeded());
        async.countDown();
      });
  });

  async.await();
}
 
Example #9
Source File: MqttClientIdTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void afterConnectClientId(TestContext context) {

  Async async = context.async();

  MqttClientOptions options = new MqttClientOptions();
  options.setClientId("myClient");
  MqttClient client = MqttClient.create(Vertx.vertx(), options);

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {

    assertTrue(c.succeeded());
    assertThat(client.clientId(), notNullValue());
    assertFalse(client.clientId().isEmpty());
    assertEquals(client.clientId(), "myClient");

    log.info("Client connected with requested client id = " + client.clientId());

    async.countDown();
  });
  async.await();
}
 
Example #10
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSslClientTruststoreTest(TestContext context) {

  this.context = context;
  JksOptions jksOptions = new JksOptions().setPath("/tls/client-truststore.jks");

  MqttClientOptions clientOptions = new MqttClientOptions()
    .setSsl(true)
    .setTrustStoreOptions(jksOptions);

  MqttClient client = MqttClient.create(vertx, clientOptions);
  client.exceptionHandler(t -> context.assertTrue(false));

  Async async = context.async();
  client.connect(MQTT_SERVER_TLS_PORT, MQTT_SERVER_HOST, s -> client.disconnect(d -> async.countDown()));
  async.await();
}
 
Example #11
Source File: MqttClientMaxMessageSizeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void decoderMaxMessageSize(TestContext context) throws InterruptedException {
  Async async = context.async();
  MqttClient client = MqttClient.create(Vertx.vertx(),
    new MqttClientOptions()
      .setMaxMessageSize(MQTT_MAX_MESSAGE_SIZE)
  );

  client.subscribeCompletionHandler(sc -> {
    log.info("SUBACK <---");
    byte[] message = new byte[MQTT_BIG_MESSAGE_SIZE];
    client.publish(MQTT_TOPIC, Buffer.buffer(message), AT_MOST_ONCE, false, false);
    log.info("PUBLISH ---> ... with big message size which should cause decoder exception");
  });

  client.exceptionHandler(t->{
    log.error("Exception raised", t);

    if (t instanceof DecoderException) {
      log.info("PUBLISH <--- message with big size");
      async.countDown();
    }
  });

  log.info("CONNECT --->");
  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    log.info("CONNACK <---");
    client.subscribe(MQTT_TOPIC, 0);
    log.info("SUBSCRIBE --->");
  });

  async.await();
}
 
Example #12
Source File: MqttClientImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * See {@link MqttClient#unsubscribe(String, Handler)} )} for more details
 */
@Override
public MqttClient unsubscribe(String topic, Handler<AsyncResult<Integer>> unsubscribeSentHandler) {

  Future<Integer> fut = unsubscribe(topic);
  if (unsubscribeSentHandler != null) {
    fut.onComplete(unsubscribeSentHandler);
  }
  return this;
}
 
Example #13
Source File: MqttClientSubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void subscribeAndReceive(TestContext context, MqttQoS qos) {

    Async async = context.async();
    MqttClient client = MqttClient.create(Vertx.vertx());

    client.publishHandler(publish -> {
        assertTrue(publish.qosLevel() == qos);
        log.info("Just received message on [" + publish.topicName() + "] payload [" + publish.payload().toString(Charset.defaultCharset()) + "] with QoS [" + publish.qosLevel() + "]");
        client.disconnect();
        async.countDown();
      });

    client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, ar -> {
      assertTrue(ar.succeeded());
      client.subscribe(MQTT_TOPIC, qos.value());
      client.publish(
        MQTT_TOPIC,
        Buffer.buffer(MQTT_MESSAGE.getBytes()),
        qos,
        false,
        false
      );

    });

    async.await();
  }
 
Example #14
Source File: MqttClientSubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void subscribe(TestContext context, MqttQoS qos) {

    this.messageId = 0;

    Async async = context.async();
    MqttClient client = MqttClient.create(Vertx.vertx());

    client.subscribeCompletionHandler(suback -> {
      assertTrue(suback.messageId() == messageId);
      assertTrue(suback.grantedQoSLevels().contains(qos.value()));
      log.info("subscribing complete for message id = " + suback.messageId() + " with QoS " + suback.grantedQoSLevels());
      client.disconnect();
      async.countDown();
    });

    client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, ar -> {
      assertTrue(ar.succeeded());

      client.subscribe(MQTT_TOPIC, qos.value(), done -> {
        assertTrue(done.succeeded());
        messageId = done.result();
        log.info("subscribing on [" + MQTT_TOPIC + "] with QoS [" + qos.value() + "] message id = " + messageId);
      });
    });

    async.await();
  }
 
Example #15
Source File: MqttClientPingTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void manualPing(TestContext context) throws InterruptedException {

  Vertx vertx = Vertx.vertx();

  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setAutoKeepAlive(false);

  log.info("Manual ping ... " + PING_NUMBER + " times timeout " + KEEPALIVE_TIMEOUT);

  count = 0;
  MqttClient client = MqttClient.create(vertx, options);
  client.connect(TestUtil.BROKER_PORT,  TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    client.pingResponseHandler(v ->{

      log.info("Pingresp <-- ");
      count++;
      if (count == PING_NUMBER) {
        vertx.cancelTimer(timerId);
        client.disconnect();
        async.countDown();
      }
    });

    vertx.setPeriodic(KEEPALIVE_TIMEOUT * 1000, t -> {
      timerId = t;
      log.info("Pingreq --> ");
      client.ping();
    });

  });

  async.await();
}
 
Example #16
Source File: MqttClientPingTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void autoPing(TestContext context) throws InterruptedException {

  Async async = context.async();
  MqttClientOptions options = new MqttClientOptions();
  options.setKeepAliveTimeSeconds(KEEPALIVE_TIMEOUT);

  log.info("Auto ping ... " + PING_NUMBER + " times timeout " + KEEPALIVE_TIMEOUT);

  count = 0;
  MqttClient client = MqttClient.create(Vertx.vertx(), options);
  client.connect(TestUtil.BROKER_PORT,  TestUtil.BROKER_ADDRESS, c -> {
    assertTrue(c.succeeded());
    client.pingResponseHandler(v -> {

      log.info("Pingresp <-- ");
      count++;
      if (count == PING_NUMBER) {
        client.disconnect();
        async.countDown();
      }
    });

  });

  async.await();
}
 
Example #17
Source File: MqttClientSslTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void clientSslTrustAllTest(TestContext context) {
  MqttClientOptions clientOptions = new MqttClientOptions()
    .setSsl(true)
    .setTrustAll(true);

  MqttClient client = MqttClient.create(vertx, clientOptions);
  client.exceptionHandler(t -> context.assertTrue(false));

  this.context = context;
  Async async = context.async();
  client.connect(MQTT_SERVER_TLS_PORT, MQTT_SERVER_HOST, s -> client.disconnect(d -> async.countDown()));
  async.await();
}
 
Example #18
Source File: MqttClientUnsubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void unsubscribe(TestContext context, MqttQoS qos) {

    this.messageId = 0;

    Async async = context.async();
    MqttClient client = MqttClient.create(Vertx.vertx());

    client.unsubscribeCompletionHandler(unsubackid -> {
      assertTrue(unsubackid == messageId);
      log.info("unsubscribing complete for message id = " + unsubackid);
      client.disconnect();
      async.countDown();
    });

    client.subscribeCompletionHandler(suback -> {
      assertTrue(suback.messageId() == messageId);
      assertTrue(suback.grantedQoSLevels().contains(qos.value()));
      log.info("subscribing complete for message id = " + suback.messageId() + " with QoS " + suback.grantedQoSLevels());

      client.unsubscribe(MQTT_TOPIC, ar2 -> {
        assertTrue(ar2.succeeded());
        messageId = ar2.result();
        log.info("unsubscribing on [" + MQTT_TOPIC + "] message id = " + messageId);
      });
    });

    client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, ar -> {
      assertTrue(ar.succeeded());

      client.subscribe(MQTT_TOPIC, qos.value(), ar1 -> {
        assertTrue(ar1.succeeded());
        messageId = ar1.result();
        log.info("subscribing on [" + MQTT_TOPIC + "] with QoS [" + qos.value() + "] message id = " + messageId);
      });
    });

    async.await();
  }
 
Example #19
Source File: MqttClientOutOfOrderAcksTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void clientSendThreePublishMessages(MqttQoS mqttQoS, TestContext context) {
  Async async = context.async(3);
  MqttClient client = MqttClient.create(vertx);

  Queue<Integer> expectOrder = new LinkedList<>();
  // order we expect to receive acknowledgment for published message
  expectOrder.add(2);
  expectOrder.add(1);
  expectOrder.add(3);

  client.publishCompletionHandler(h -> {
    context.assertEquals(h.intValue(), expectOrder.poll());
    log.info("[CLIENT] Publish completed for message with id: " + h);
    async.countDown();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {

    // publish QoS = 1 message three times
    for (int i = 0; i < 3; i++)
      client.publish(MQTT_TOPIC,
        Buffer.buffer(MQTT_MESSAGE.getBytes()),
        mqttQoS,
        false,
        false, h -> log.info("[CLIENT] publishing message id = " + h.result()));
  });

  async.await();
  client.disconnect();
}
 
Example #20
Source File: MqttClientProvider.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
public void initMqttClient(VertxMqttClient mqttClient, MqttClientProperties properties) {
    MqttClient client = MqttClient.create(vertx, properties.getOptions());
    client.connect(properties.getPort(), properties.getHost(), result -> {
        if (!result.succeeded()) {
            log.warn("connect mqtt [{}] error", properties.getId(), result.cause());
        } else {
            mqttClient.setClient(client);
        }
    });
}
 
Example #21
Source File: MqttClientConnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connackNotOk(TestContext context) {
  Async async = context.async();
  Async asyncServer = context.async();
  Vertx vertx = Vertx.vertx();

  MqttServer server = MqttServer.create(vertx);
  server.endpointHandler(endpoint -> {
    endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
  });
  server.listen(MqttServerOptions.DEFAULT_PORT, context.asyncAssertSuccess(v -> asyncServer.complete()));
  asyncServer.await();

  MqttClient client = MqttClient.create(vertx);
  client.closeHandler(v -> {
    // when server replies with "negative" CONNACK, this handler should not be called
    // the failure is just part of the connectHandler
    context.fail();
  });

  client.connect(MqttClientOptions.DEFAULT_PORT, MqttClientOptions.DEFAULT_HOST, c -> {
    assertTrue(c.failed());
    assertTrue(c.cause() instanceof MqttConnectionException);
    MqttConnectionException connEx = (MqttConnectionException) c.cause();
    assertEquals(connEx.code(), MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
    assertFalse(client.isConnected());
    async.complete();
  });

  async.await();
}
 
Example #22
Source File: MqttClientTopicValidationTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Execute a test of topic validation on public
 *
 * @param topicName topic name
 * @param mustBeValid if it should be valid or not
 * @param context
 */
public void testPublish(String topicName, boolean mustBeValid, TestContext context) {

  log.info(String.format("test publishing in \"%s\" topic", topicName));
  Async async = context.async(2);
  MqttClient client = MqttClient.create(Vertx.vertx());

  client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
    Assert.assertTrue(c.succeeded());

    client.publish(
      topicName,
      Buffer.buffer(MQTT_MESSAGE.getBytes()),
      MqttQoS.AT_MOST_ONCE,
      false,
      false,
      ar1 -> {
        assertThat(ar1.succeeded(), is(mustBeValid));
        log.info("publishing message id = " + ar1.result());
        async.countDown();
        client
          .disconnect(ar -> {
            Assert.assertTrue(ar.succeeded());
            async.countDown();
          });
      });
  });

  async.await();
}
 
Example #23
Source File: MqttClientTopicValidationTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
public void testSubscribe(String topicFilter, boolean mustBeValid, TestContext context) {

    log.info(String.format("test subscribing for \"%s\" topic", topicFilter));

    Async async = context.async(2);
    MqttClient client = MqttClient.create(Vertx.vertx());

    client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, c -> {
      Assert.assertTrue(c.succeeded());

      client.subscribe(
        topicFilter,
        0,
        ar -> {
          assertThat(ar.succeeded(), is(mustBeValid));
          log.info("subscribe message id = " + ar.result());
          async.countDown();
          client
            .disconnect(ar1 -> {
              Assert.assertTrue(ar1.succeeded());
              async.countDown();
            });
        });
    });

    async.await();
  }
 
Example #24
Source File: MqttClientPublishTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void publish(TestContext context, MqttQoS qos) {

    this.messageId = 0;

    Async async = context.async();
    MqttClient client = MqttClient.create(Vertx.vertx());

    client.publishCompletionHandler(pubid -> {
      assertTrue(pubid == messageId);
      log.info("publishing complete for message id = " + pubid);
      client.disconnect();
      async.countDown();
    });

    client.connect(TestUtil.BROKER_PORT, TestUtil.BROKER_ADDRESS, ar -> {

      assertTrue(ar.succeeded());

      client.publish(
        MQTT_TOPIC,
        Buffer.buffer(MQTT_MESSAGE.getBytes()),
        qos,
        false,
        false,
        ar1 -> {
          assertTrue(ar.succeeded());
          messageId = ar1.result();
          log.info("publishing message id = " + messageId);
        }
      );
    });

    async.await();
  }
 
Example #25
Source File: VertxMqttClientExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for unsubscribeCompletionHandler method demonstration
 *
 * @param client
 */
public void example7(MqttClient client) {
  client
    .unsubscribeCompletionHandler(id -> {
      System.out.println("Id of just received UNSUBACK packet is " + id);
    });
  client.subscribe("temp", 1);
  client.unsubscribe("temp");
}
 
Example #26
Source File: MqttProducerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));


            client.connect(PORT,HOST, asyncResult -> {
                Runnable publishTask = () -> {
                    Buffer buffer = Buffer.buffer("发布数据" + PUBLISH_COUNT.incrementAndGet());
                    client.publish("/hello",buffer,
                            MqttQoS.EXACTLY_ONCE, true, true,
                            asyncResult1 -> {
                                if (asyncResult1.succeeded()) {
                                    logger.info("publish {}", asyncResult1);
                                }
                            }
                    );
                };
                Executors.newScheduledThreadPool(1)
                        .scheduleAtFixedRate(publishTask, 0, 15, TimeUnit.MILLISECONDS);
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #27
Source File: MqttConsumerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));

            client.connect(PORT,HOST,s -> {
                client.publishHandler(response -> {
                    String message = new String(response.payload().getBytes());
                    logger.info("接收到消息: {} from topic {}", message, response.topicName());
                });

                client.subscribe("#", MqttQoS.AT_LEAST_ONCE.value(), resp -> {
                    logger.info("subscribe {}", resp);
                });
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #28
Source File: MqttTopicEventChannel.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
public MqttTopicEventChannel(String name, MqttClient session, ContentCodec codec) {
    super(EventMode.TOPIC, name);
    this.session = session;
    this.codec = codec;
    EventHandler handler = new EventHandler();
    this.session.publishHandler(handler);
}
 
Example #29
Source File: MqttEventChannelTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Before
public void start() throws Exception {
    vertx = Vertx.vertx();
    session = MqttClient.create(vertx);
    CountDownLatch latch = new CountDownLatch(1);
    session.connect(1883, "localhost", (connect) -> {
        latch.countDown();
    });
    latch.await();
}
 
Example #30
Source File: VertxMqttClientExamples.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
/**
 * Example for demonstration of how {@link MqttClient#connect(int, String, Handler)} and  {@link MqttClient#disconnect()} methods
 * should be used
 *
 * @param vertx
 */
public void example1(Vertx vertx) {
  MqttClient client = MqttClient.create(vertx);

  client.connect(1883, "mqtt.eclipse.org", s -> {
    client.disconnect();
  });
}