/** * Invoke from the command line with a single parameter, the broker URI, * e.g. tcp://mybroker:1883. */ public static void main(String args[]) { MqttPublisher publisher = null; try { publisher = new MqttPublisher(args[0]); /** * Connect the newly created publisher to the supplied broker. */ publisher.connect(); /** * Publish an "Arrival" message. */ publisher.publishMessage( "Flight Times/LHR/Air Freedom/Arrivals/Flight 1024", (byte) 2, "Arrived"); /** * Sleep for 1 second waiting to receive notification of * publication. Real applications should use appropriate * inter-thread signaling mechanisms such as wait/notify, * cyclic barriers or latches. */ Thread.sleep(1000); } catch (MqttException exception) { System.err.println("Exception occurred during either instantiation, connection, or publication: " + exception.getMessage()); } catch (InterruptedException exception) { System.err.println("Interrupted while waiting for publication: " + exception.getMessage()); } finally { try { /** * Close the publisher if instantiated. */ if (publisher != null) { publisher.disconnectClient(); } } catch (MqttException exception) { System.err.println("Exception occurred closing publisher: " + exception.getMessage()); } } } /** * Construct a new MqttPublisher containing an unconnected MqttClient. * * @param brokerURL * Broker URL to (eventually) connect to. * @throws MqttException * If an underlying MQTT error occurs instantiating the client * object. */ private MqttPublisher(String brokerURL) throws MqttException { this.brokerURL = brokerURL; this.client = createClient(); } /** * Publish a string as a message in byte form with the given quality of * service to the given topic. */ public void publishMessage(String topic, byte qos, String message) throws MqttException { client.publish(topic, new MqttPayload(message.getBytes(), 0), qos, false); }