Java Code Examples for io.vertx.mqtt.MqttClient#create()
The following examples show how to use
io.vertx.mqtt.MqttClient#create() .
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: MqttClientConnectTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 2
Source File: MqttClientConnectTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 3
Source File: VertxMqttServerProviderTest.java From jetlinks-community with Apache License 2.0 | 6 votes |
@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 4
Source File: MqttClientSslTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 5
Source File: MqttClientIdTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 6
Source File: MqttClientIdTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 7
Source File: MqttClientMaxMessageSizeTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@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 8
Source File: MqttClientOutOfOrderAcksTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 9
Source File: MqttClientUnsubscribeTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 10
Source File: MqttClientTopicValidationTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 11
Source File: MqttClientPingTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@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 12
Source File: MqttClientPingTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@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 13
Source File: MqttClientSubscribeTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 14
Source File: MqttClientTopicValidationTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
/** * 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 15
Source File: VertxMqttClientExamples.java From vertx-mqtt with Apache License 2.0 | 5 votes |
/** * 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(); }); }
Example 16
Source File: MqttEventChannelTestCase.java From jstarcraft-core with Apache License 2.0 | 5 votes |
@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 17
Source File: MqttConsumerBootstrap.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
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 18
Source File: MqttProducerBootstrap.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
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 19
Source File: VertxMqttServerProviderTest.java From jetlinks-community with Apache License 2.0 | 4 votes |
@Test void testMessage() { MqttClient client = MqttClient.create(vertx); client.publishHandler(msg -> { System.out.println(msg.topicName() + " " + msg.payload().toString("utf-8")); }); client.connect(1811, "127.0.0.1", result -> { if (!result.succeeded()) { result.cause().printStackTrace(); } else { client.publish("/test", Buffer.buffer("test"), MqttQoS.AT_MOST_ONCE, false, false); client.publish("/test", Buffer.buffer("test1"), MqttQoS.AT_LEAST_ONCE, false, false); client.publish("/test", Buffer.buffer("test2"), MqttQoS.EXACTLY_ONCE, false, false); } }); mqttServer .handleConnection() .flatMap(conn -> { Flux<MqttPublishing> publishingFlux = conn.handleMessage(); conn.accept(); return conn.publish(SimpleMqttMessage.builder() .qosLevel(2) .topic("/test2") .payload(Unpooled.wrappedBuffer("test".getBytes())) .build()) .thenMany(publishingFlux); // return publishingFlux; }) .map(pub -> pub.getMessage().getPayload().toString(StandardCharsets.UTF_8)) .take(3) .as(StepVerifier::create) .expectNext("test", "test1", "test2") .verifyComplete(); }
Example 20
Source File: VertxMqttDeviceClient.java From device-simulator with Apache License 2.0 | 4 votes |
private void doConnect(FluxSink<ClientSession> sink, int index, MqttClientConfiguration configuration, MqttClientOptions options, MqttClientSession session) { MqttAuthInfo authInfo = configuration.getAuthGenerator().generate(index); options.setClientId(authInfo.getClientId()); options.setUsername(authInfo.getUsername()); options.setPassword(authInfo.getPassword()); MqttClient client = MqttClient.create(vertx, options); client.connect(configuration.getPort(), configuration.getHost(), result -> { if (result.succeeded()) { MqttClientSession mqttClientSession = session == null ? new MqttClientSession() : session; mqttClientSession.client = client; client.closeHandler((r) -> { if (!mqttClientSession.manualClose) { if (mqttClientSession.retryTimes.incrementAndGet() >= configuration.getOptions().getReconnectAttempts()) { return; } Mono.delay(Duration.ofMillis(Math.max(options.getReconnectInterval(), 1000))) .subscribe(ignore -> doConnect(sink, index, configuration, options, mqttClientSession)); } }); client.publishHandler(message -> { mqttClientSession.processor.onNext( SimpleMqttMessage.builder() .messageId(message.messageId()) .payload(message.payload().getByteBuf()) .qosLevel(message.qosLevel().value()) .topic(message.topicName()) .dup(message.isDup()) .retain(message.isRetain()) .build() ); }); if (session == null) { sink.next(mqttClientSession); } } else { sink.error(result.cause()); } }); }