org.eclipse.paho.client.mqttv3.MqttAsyncClient Java Examples
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttAsyncClient.
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: MqttClientManager.java From micro-integrator with Apache License 2.0 | 6 votes |
public MqttAsyncClient getMqttClient(String identifier) { if (tenantLoadingFlagMap.containsKey(identifier)) { //this is manually tenant loading case should return the client return mqttClientMap.get(identifier); } else { MqttAsyncCallback callback = mqttCallbackMap.get(identifier); //this is the case where recreation of same bounded inbound endpoint for server host //server port, client id String msg = "Client ID: " + callback.getMqttConnectionConsumer().getMqttAsyncClient().getClientId() + " Server Host: " + callback.getMqttConnectionConsumer().getMqttConnectionFactory().getServerHost() + " Server Port: " + callback.getMqttConnectionConsumer().getMqttConnectionFactory().getServerPort() + " is bound to existing MQTT Inbound Endpoint."; log.error(msg); throw new SynapseException(msg); } }
Example #2
Source File: SocketProxyTest.java From rxmqtt with Apache License 2.0 | 6 votes |
@Test public void whenPahoConnectToBrokerViaProxyThenItWorks() throws Throwable { // Wait a second Thread.sleep(1000); // Create the client MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); // Connect, publish, disconnect AsyncPahoUtils.connect(asyncClient); AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes()); AsyncPahoUtils.disconnect(asyncClient); // Check we received a message Assert.assertEquals(1, broker.getMessages().size()); }
Example #3
Source File: AwsIotMqttConnection.java From aws-iot-device-sdk-java with Apache License 2.0 | 6 votes |
public AwsIotMqttConnection(AbstractAwsIotClient client, SocketFactory socketFactory, String serverUri) throws AWSIotException { super(client); this.socketFactory = socketFactory; messageListener = new AwsIotMqttMessageListener(client); clientListener = new AwsIotMqttClientListener(client); try { mqttClient = new MqttAsyncClient(serverUri, client.getClientId(), new MemoryPersistence()); mqttClient.setCallback(clientListener); } catch (MqttException e) { throw new AWSIotException(e); } }
Example #4
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 6 votes |
/** * Unsubscribes from a topic on the given connection, but does not alter the subscriber list. * * @param client The client connection * @param topic The topic to unsubscribe from * @return Completes with true if successful. Completes with false if no broker connection is established. * Exceptionally otherwise. */ protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) { logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { if (client.isConnected()) { client.unsubscribe(topic, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error unsubscribing topic from broker", e); future.completeExceptionally(e); } return future; }
Example #5
Source File: AbstractMqttClient.java From xian with Apache License 2.0 | 6 votes |
/** * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null */ public MqttAsyncClient connectBroker() { LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); try { sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence); connOpts = new MqttConnectOptions(); connOpts.setAutomaticReconnect(true); connOpts.setServerURIs(serverURIs); connOpts.setUserName(userName); connOpts.setPassword(getPwd()); connOpts.setCleanSession(cleanSession); connOpts.setMaxInflight(1000 /**默认的值是10,对于我们来说这个值太小!*/); connOpts.setKeepAliveInterval(keepAliveInterval); sampleClient.setCallback(getCallback(this)); sampleClient.connect(connOpts).waitForCompletion(60 * 1000); LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); return sampleClient; } catch (MqttException me) { throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me); } }
Example #6
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings({ "null", "unused" }) public CompletableFuture<Boolean> unsubscribe(String topic, MqttMessageSubscriber subscriber) { synchronized (subscribers) { final @Nullable List<MqttMessageSubscriber> list = subscribers.get(topic); if (list == null) { return CompletableFuture.completedFuture(true); } list.remove(subscriber); if (!list.isEmpty()) { return CompletableFuture.completedFuture(true); } // Remove from subscriber list subscribers.remove(topic); // No more subscribers to this topic. Unsubscribe topic on the broker MqttAsyncClient client = this.client; if (client != null) { return unsubscribeRaw(client, topic); } else { return CompletableFuture.completedFuture(false); } } }
Example #7
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 6 votes |
/** * Subscribes to a topic on the given connection, but does not alter the subscriber list. * * @param topic The topic to subscribe to. * @return Completes with true if successful. Exceptionally otherwise. */ protected CompletableFuture<Boolean> subscribeRaw(String topic) { logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host); CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); try { MqttAsyncClient client = this.client; if (client != null && client.isConnected()) { client.subscribe(topic, qos, future, actionCallback); } else { future.complete(false); } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error subscribing to topic {}", topic, e); future.completeExceptionally(e); } return future; }
Example #8
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 6 votes |
/** * Add a new message consumer to this connection. Multiple subscribers with the same * topic are allowed. This method will not protect you from adding a subscriber object * multiple times! * * If there is a retained message for the topic, you are guaranteed to receive a callback * for each new subscriber, even for the same topic. * * @param topic The topic to subscribe to. * @param subscriber The callback listener for received messages for the given topic. * @return Completes with true if successful. Completes with false if not connected yet. Exceptionally otherwise. */ public CompletableFuture<Boolean> subscribe(String topic, MqttMessageSubscriber subscriber) { CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(); synchronized (subscribers) { TopicSubscribers subscriberList = subscribers.getOrDefault(topic, new TopicSubscribers(topic)); subscribers.put(topic, subscriberList); subscriberList.add(subscriber); } final MqttAsyncClient client = this.client; if (client == null) { future.completeExceptionally(new Exception("No MQTT client")); return future; } if (client.isConnected()) { try { client.subscribe(topic, qos, future, actionCallback); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { future.completeExceptionally(e); } } else { // The subscription will be performed on connecting. future.complete(false); } return future; }
Example #9
Source File: MqttPlugin.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void init(MqttPluginConfiguration configuration) { retryInterval = configuration.getRetryInterval(); mqttClientOptions = new MqttConnectOptions(); mqttClientOptions.setCleanSession(false); mqttClientOptions.setMaxInflight(configuration.getMaxInFlight()); mqttClientOptions.setAutomaticReconnect(true); String clientId = configuration.getClientId(); if (StringUtils.isEmpty(clientId)) { clientId = UUID.randomUUID().toString(); } if (!StringUtils.isEmpty(configuration.getAccessToken())) { mqttClientOptions.setUserName(configuration.getAccessToken()); } try { mqttClient = new MqttAsyncClient("tcp://" + configuration.getHost() + ":" + configuration.getPort(), clientId); } catch (Exception e) { log.error("Failed to create mqtt client", e); throw new RuntimeException(e); } // connect(); }
Example #10
Source File: Bridge.java From MQTTKafkaBridge with Apache License 2.0 | 6 votes |
private void connect(String serverURI, String clientId, String zkConnect) throws MqttException { mqtt = new MqttAsyncClient(serverURI, clientId); mqtt.setCallback(this); IMqttToken token = mqtt.connect(); Properties props = new Properties(); //Updated based on Kafka v0.8.1.1 props.put("metadata.broker.list", "localhost:9092"); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("partitioner.class", "example.producer.SimplePartitioner"); props.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(props); kafkaProducer = new Producer<String, String>(config); token.waitForCompletion(); logger.info("Connected to MQTT and Kafka"); }
Example #11
Source File: MqttAsyncCallback.java From micro-integrator with Apache License 2.0 | 5 votes |
public MqttAsyncCallback(MqttAsyncClient mqttAsyncClient, MqttInjectHandler injectHandler, MqttConnectionFactory confac, MqttConnectOptions connectOptions, Properties mqttProperties) { this.injectHandler = injectHandler; this.mqttAsyncClient = mqttAsyncClient; this.confac = confac; this.connectOptions = connectOptions; this.mqttProperties = mqttProperties; }
Example #12
Source File: ToxiproxyConnectivityITCase.java From rxmqtt with Apache License 2.0 | 5 votes |
@Ignore @Test public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); }
Example #13
Source File: SocketProxyTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenProxyDisabledThenPahoDisconnect() throws Throwable { // Wait a second Thread.sleep(1000); // Create the client MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); // Connect, publish AsyncPahoUtils.connect(asyncClient, options); AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes()); AsyncPahoUtils.subscribe(asyncClient, "topical2", (t, m) -> {}); Assert.assertEquals(1, broker.getMessages().size()); // Disable proxy brokerProxy.disable(); Thread.sleep(3000); // Check disconnected Assert.assertFalse(asyncClient.isConnected()); }
Example #14
Source File: SocketProxyTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenAutoReconnectThenPahoReconnectsAfterProxyDisable() throws Throwable { // Create the client MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); // Connect, publish AsyncPahoUtils.connect(asyncClient, options); AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes()); AsyncPahoUtils.subscribe(asyncClient, "topical2", (t, m) -> {}); Assert.assertEquals(1, broker.getMessages().size()); // Disable proxy brokerProxy.disable(); Thread.sleep(5000); // Check disconnected Assert.assertFalse(asyncClient.isConnected()); // Re-enable brokerProxy.enable(); Thread.sleep(10000); AsyncPahoUtils.publish(asyncClient, "topical", "Test message".getBytes()); // Check connected Assert.assertTrue(asyncClient.isConnected()); }
Example #15
Source File: MoquetteProxyContext.java From cloud-pubsub-mqtt-proxy with Apache License 2.0 | 5 votes |
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. */ public MoquetteProxyContext() { try { this.dataStore = new MqttDefaultFilePersistence(); this.client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
Example #16
Source File: MoquetteProxyContext.java From cloud-pubsub-mqtt-proxy with Apache License 2.0 | 5 votes |
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. * * @param persistenceDir the location of the persistent storage used by the MQTT client library. */ public MoquetteProxyContext(String persistenceDir) { try { dataStore = new MqttDefaultFilePersistence(checkNotNull(persistenceDir)); client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
Example #17
Source File: Engine.java From winthing with Apache License 2.0 | 5 votes |
@Inject public Engine(final Gson gson, final Registry registry, final Config config, final MqttClientPersistence persistence) throws MqttException { String topicPrefix = config.getString(Settings.TOPIC_PREFIX).replaceFirst("^/+", ""); if (!topicPrefix.isEmpty() && !topicPrefix.endsWith("/")) { topicPrefix += "/"; } this.topicPrefix = topicPrefix; this.reconnectInterval = Duration.ofSeconds(config.getLong(Settings.RECONNECT_INTERVAL)); this.gson = Objects.requireNonNull(gson); this.registry = Objects.requireNonNull(registry); this.client = new MqttAsyncClient( "tcp://" + config.getString(Settings.BROKER_URL), config.getString(Settings.CLIENT_ID), persistence ); this.client.setCallback(this); { final String username = config.getString(Settings.BROKER_USERNAME); if (username != null && !username.isEmpty()) { this.options.setUserName(username); } } { final String password = config.getString(Settings.BROKER_PASSWORD); if (password != null && !password.isEmpty()) { this.options.setPassword(password.toCharArray()); } } this.options.setCleanSession(true); }
Example #18
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Unsubscribe from all topics * * @return Returns a future that completes as soon as all subscriptions have been canceled. */ public CompletableFuture<Void> unsubscribeAll() { MqttAsyncClient client = this.client; List<CompletableFuture<Boolean>> futures = new ArrayList<>(); if (client != null) { subscribers.forEach((topic, subList) -> { futures.add(unsubscribeRaw(client, topic)); }); subscribers.clear(); } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); }
Example #19
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Publish a message to the broker with the given QoS and retained flag. * * @param topic The topic * @param payload The message payload * @param qos The quality of service for this message * @param retain Set to true to retain the message on the broker * @param listener A listener to be notified of success or failure of the delivery. */ public void publish(String topic, byte[] payload, int qos, boolean retain, MqttActionCallback listener) { MqttAsyncClient client_ = client; if (client_ == null) { listener.onFailure(topic, new MqttException(0)); return; } try { IMqttDeliveryToken deliveryToken = client_.publish(topic, payload, qos, retain, listener, actionCallback); logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { listener.onFailure(topic, new MqttException(e)); } }
Example #20
Source File: MqttBrokerConnection.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Publish a message to the broker with the given QoS and retained flag. * * @param topic The topic * @param payload The message payload * @param qos The quality of service for this message * @param retain Set to true to retain the message on the broker * @param listener An optional listener to be notified of success or failure of the delivery. * @return Returns a future that completes with a result of true if the publishing succeeded and completes * exceptionally on an error or with a result of false if no broker connection is established. */ public CompletableFuture<Boolean> publish(String topic, byte[] payload, int qos, boolean retain) { MqttAsyncClient client = this.client; if (client == null) { return CompletableFuture.completedFuture(false); } // publish message asynchronously CompletableFuture<Boolean> f = new CompletableFuture<Boolean>(); try { client.publish(topic, payload, qos, retain, f, actionCallback); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { f.completeExceptionally(new MqttException(e)); } return f; }
Example #21
Source File: MqttConnection.java From bce-sdk-java with Apache License 2.0 | 5 votes |
public MqttConnection(String serverURI, String clientId, String userName, String password, SocketFactory socketFactory, MqttCallback mqttCallbackListener, IMqttActionListener mqttMessageListener) throws MqttException { if (serverURI == null || mqttCallbackListener == null || mqttMessageListener == null) { throw new IllegalArgumentException("serverURI, mqttCallbackListener, mqttMessageListener can't be null!"); } this.mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, new MemoryPersistence()); this.mqttAsyncClient.setManualAcks(true); this.connectionOptions = new MqttConnectOptions(); this.initOptions(userName, password, socketFactory); this.mqttMessageListener = mqttMessageListener; this.mqttAsyncClient.setCallback(mqttCallbackListener); }
Example #22
Source File: MqttAsyncClientFactory.java From jframe with Apache License 2.0 | 5 votes |
@Override public IMqttAsyncClient create() throws Exception { String broker = conf.getConf(id, MqttClientConf.F_mqtt_broker); MqttAsyncClient mqttClient = new MqttAsyncClient(broker, createClientId(), createPersistence()); mqttClient.connect(createConnectOptions()).waitForCompletion(); return mqttClient; }
Example #23
Source File: MQTTWrapper.java From gsn with GNU General Public License v3.0 | 5 votes |
@Override public boolean initialize() { try { addressBean = getActiveAddressBean( ); serverURI = addressBean.getPredicateValue("uri"); if ( serverURI == null || serverURI.trim().length() == 0 ) { logger.error( "The uri parameter is missing from the MQTT wrapper, initialization failed." ); return false; } clientID = addressBean.getPredicateValue("client_id"); if ( clientID == null || clientID.trim().length() == 0 ) { logger.error( "The client_id parameter is missing from the MQTT wrapper, initialization failed." ); return false; } topic = addressBean.getPredicateValue("topic"); if ( topic == null || topic.trim().length() == 0 ) { logger.error( "The topic parameter is missing from the MQTT wrapper, initialization failed." ); return false; } qos = addressBean.getPredicateValueAsInt("qos", 0); if (qos < 0 || qos > 2) { logger.error( "The qos parameter from MQTT wrapper can be 0, 1 or 2 (found "+qos+"), initialization failed." ); return false; } client = new MqttAsyncClient(serverURI, clientID); client.setCallback(this); client.connect(); }catch (Exception e){ logger.error("Error in instanciating MQTT broker with "+topic+" @ "+serverURI,e); return false; } return true; }
Example #24
Source File: SensorsManager.java From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License | 5 votes |
public SensorsManager(final MqttAsyncClient asyncClient, final String boardCommandsTopic, final String boardDataBaseTopic, final String encoding) { this.boardCommandsTopic = boardCommandsTopic; this.boardDataBaseTopic = boardDataBaseTopic; this.encoding = encoding; this.asyncClient = asyncClient; // Build and save the topic names that we will use to publish the data from the sensors this.earthHumidityTopic = this.boardDataBaseTopic.concat(SENSOR_EARTH_HUMIDITY); final String sunlightDataBaseTopic = boardDataBaseTopic.concat(SENSOR_SUNLIGHT); this.visibleLightTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "visiblelight"); this.infraredLightTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "ir"); this.ultraVioletIndexTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "uv"); }
Example #25
Source File: MqttConnectionConsumer.java From micro-integrator with Apache License 2.0 | 5 votes |
public MqttConnectionConsumer(MqttConnectOptions connectOptions, MqttAsyncClient mqttAsyncClient, MqttConnectionFactory confac, Properties mqttProperties, String name) { this.name = name; this.connectOptions = connectOptions; this.mqttAsyncClient = mqttAsyncClient; this.confac = confac; this.mqttProperties = mqttProperties; }
Example #26
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenBrokerIsRestartedThenWithAutoReconnectClientIsReconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(true); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(5000); Assert.assertTrue(observableClient.isConnected()); }
Example #27
Source File: MqttInput.java From neoscada with Eclipse Public License 1.0 | 5 votes |
private String makeClientId ( final String clientId ) { if ( clientId != null ) { return clientId; } return MqttAsyncClient.generateClientId (); }
Example #28
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenBrokerIsStoppedThenClientIsDisconnected() throws Throwable { // Create client with re-connect and dirty sessions MqttConnectOptions options = new MqttConnectOptions(); options.setAutomaticReconnect(false); options.setCleanSession(false); options.setKeepAliveInterval(1); options.setConnectionTimeout(1); String proxyUrl = "tcp://" + PROXY_HOST + ":" + PROXY_PORT; MqttAsyncClient asyncClient = new MqttAsyncClient(proxyUrl, "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, options); // Connect observableClient.connect().blockingAwait(); Assert.assertTrue(observableClient.isConnected()); // Stop the broker proxy this.brokerProxy.disable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); // Restart the broker proxy this.brokerProxy.enable(); Thread.sleep(3000); Assert.assertFalse(observableClient.isConnected()); }
Example #29
Source File: Factory.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
public IMqttAsyncClient getMqttAsyncClient (String protocol, String mqttUrl, String clientID, MemoryPersistence persistence) throws MqttException { if(protocol.equals("tcp")) return new MqttAsyncClient(mqttUrl, clientID, persistence); else if (protocol.equals("ws") || protocol.equals("wss")) return new MqttWebSocketAsyncClient (mqttUrl, clientID, persistence); else return null; }
Example #30
Source File: MoquetteConnectivityTest.java From rxmqtt with Apache License 2.0 | 5 votes |
@Test public void whenWeConnectObservableClientToTestBrokerThenItCanPublishMessages() throws Throwable { // Connect, publish, disconnect MqttAsyncClient asyncClient = new MqttAsyncClient(this.broker.toUrl(), "test-client-id", new MemoryPersistence()); ObservableMqttClient observableClient = observableClient(asyncClient, new MqttConnectOptions()); observableClient.connect().blockingAwait(); observableClient.publish("topical", PublishMessage.create("Test message".getBytes(), 2, false)).blockingGet(); observableClient.disconnect().blockingAwait(); // Check we received a message Assert.assertEquals(1, broker.getMessages().size()); }