Java Code Examples for io.vertx.mqtt.MqttClient#connect()
The following examples show how to use
io.vertx.mqtt.MqttClient#connect() .
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: 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 2
Source File: MqttClientConnectTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 3
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 4
Source File: MqttClientConnectTest.java From vertx-mqtt with Apache License 2.0 | 6 votes |
@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 5
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 6
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 7
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 8
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 9
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 10
Source File: MqttClientSubscribeTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 11
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 12
Source File: MqttClientConnectTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@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 13
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 14
Source File: VertxMqttServerProviderTest.java From jetlinks-community with Apache License 2.0 | 5 votes |
@Test void testSub() { MqttClient client = MqttClient.create(vertx); client.connect(1811, "127.0.0.1", result -> { if (!result.succeeded()) { result.cause().printStackTrace(); } else { client.subscribe("/test", 1, res -> { System.out.println(res.result()); }); } }); mqttServer .handleConnection() .flatMap(conn -> { Flux<MqttSubscription> publishingFlux = conn.handleSubscribe(true); conn.accept(); return publishingFlux; }) .flatMapIterable(pub -> pub.getMessage().topicSubscriptions()) .map(MqttTopicSubscription::topicName) .take(1) .as(StepVerifier::create) .expectNext("/test") .verifyComplete(); }
Example 15
Source File: MqttClientSslTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
@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 16
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 17
Source File: MqttClientPublishTest.java From vertx-mqtt with Apache License 2.0 | 5 votes |
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 18
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 19
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 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()); } }); }