當前位置: 首頁>>代碼示例>>Java>>正文


Java MqttClient.publish方法代碼示例

本文整理匯總了Java中org.eclipse.paho.client.mqttv3.MqttClient.publish方法的典型用法代碼示例。如果您正苦於以下問題:Java MqttClient.publish方法的具體用法?Java MqttClient.publish怎麽用?Java MqttClient.publish使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.eclipse.paho.client.mqttv3.MqttClient的用法示例。


在下文中一共展示了MqttClient.publish方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testMQtt

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
@Test
public void testMQtt() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    MqttClient client = new MqttClient("tcp://localhost:" + MQTT_PORT, MqttClient.generateClientId(), new MemoryPersistence());
    client.connect();
    MqttComponent mqtt = new MqttComponent();
    mqtt.client = client;
    Publisher<byte[]> fromTopic = mqtt.from("input", byte[].class);
    Subscriber<byte[]> toTopic = mqtt.to("output", byte[].class);
    Flux.from(fromTopic)
        .log()
        .subscribe(toTopic);
    
    client.subscribe("output", (topic, message) -> {
        result = new Integer(new String(message.getPayload()));
        latch.countDown();
    });
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    latch.await(100, TimeUnit.SECONDS);
    Assert.assertEquals(2, result, 0.1);
    client.disconnect();
    client.close();
}
 
開發者ID:cschneider,項目名稱:reactive-components,代碼行數:25,代碼來源:MqttTest.java

示例2: connectPublish

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public synchronized void connectPublish(final String userKeyString, final String deviceKeyString, final String status) {

        try {
            final MqttClient client = connect();
            if (client == null || !client.isConnected()) {
                return;
            }
            MqttMessage message = new MqttMessage();
            message.setRetained(false);
            message.setPayload((userKeyString + "," + deviceKeyString + "," + status).getBytes());
            Utils.printLog(context,TAG, "UserKeyString,DeviceKeyString,status:" + userKeyString + "," + deviceKeyString + "," + status);
            message.setQos(0);
            client.publish(STATUS, message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
 
開發者ID:AppLozic,項目名稱:Applozic-Android-Chat-Sample,代碼行數:19,代碼來源:ApplozicMqttService.java

示例3: publishTopic

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context,TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:AppLozic,項目名稱:Applozic-Android-Chat-Sample,代碼行數:17,代碼來源:ApplozicMqttService.java

示例4: connectPublish

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public synchronized void connectPublish(final String userKeyString, final String deviceKeyString, final String status) {

        try {
            final MqttClient client = connect();
            if (client == null || !client.isConnected()) {
                return;
            }
            MqttMessage message = new MqttMessage();
            message.setRetained(false);
            message.setPayload((userKeyString + "," + deviceKeyString + "," + status).getBytes());
            Utils.printLog(context, TAG, "UserKeyString,DeviceKeyString,status:" + userKeyString + "," + deviceKeyString + "," + status);
            message.setQos(0);
            client.publish(STATUS, message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
 
開發者ID:AppLozic,項目名稱:Applozic-Android-Chat-Sample,代碼行數:19,代碼來源:ApplozicMqttService.java

示例5: publishTopic

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:AppLozic,項目名稱:Applozic-Android-Chat-Sample,代碼行數:17,代碼來源:ApplozicMqttService.java

示例6: main

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public static void main(String args[]) {
    String topic = "iot/iot";
    String content = "Hello ith";
    int qos = 2;
    String broker = "tcp://127.0.0.1:1883";
    String clientId = "sample";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker");
        sampleClient.connect(connOpts);
        System.out.println("connected");
        System.out.println("Publishing meessage: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
        sampleClient.disconnect();
        System.out.println("Disconnected");
        System.exit(0);
    } catch (MqttException e){
        System.out.println("reason " + e.getReasonCode());
        System.out.println("msg " + e.getMessage());
        System.out.println("loc " + e.getLocalizedMessage());
        System.out.println("cause " + e.getCause());
        System.out.println("exxcep " + e);
    }

}
 
開發者ID:dream-lab,項目名稱:echo,代碼行數:33,代碼來源:MQTTPublisher.java

示例7: publish

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
/**
 * Publishes a single topic on the MQTT broker
 * 
 * @param mqttClient the broker connection
 * @param topic the topic to publish (relative to configured topic root)
 * @param data the data to publish
 * @param retained if the data should be retained
 * @throws MqttPersistenceException
 * @throws MqttException
 */
private void publish (MqttClient mqttClient, String topic, String data, boolean retained) throws MqttPersistenceException, MqttException
{
    if ( LOG.isDebugEnabled() ) {
        LOG.debug(String.format("Publishing '%s' to topic '%s' (retained = %s)", data, topic, retained));
    }

    MqttMessage msg = new MqttMessage(data.getBytes());
    msg.setQos(configuration.getMqttQos());
    msg.setRetained(retained);
    mqttClient.publish(configuration.getMqttTopicRoot() + topic, msg);
}
 
開發者ID:zazaz-de,項目名稱:iot-device-bosch-indego-controller,代碼行數:22,代碼來源:MqttIndegoAdapter.java

示例8: main

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public static void main(String[] args) {

        String topic = "MQTT Examples";
        String content = "Message from MqttPublishSample";
        int qos = 0;
        String broker = "tcp://localhost:8080";
        String clientId = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: " + content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
 
開發者ID:lujianbo,項目名稱:moonlight-mqtt,代碼行數:34,代碼來源:Client.java

示例9: main

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public static void main(String[] args) {

        String topic = "java";
        String content = "Message from MqttPublishSample";
        int qos = 2;
        String broker = "tcp://127.0.0.1:1883";
        String clientId = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: " + content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
 
開發者ID:projectsrepos,項目名稱:jim,代碼行數:34,代碼來源:MqttPublishSample.java

示例10: publish

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
/**
 * mqtt command publish handle
 * 
 * @param command
 */
private void publish(MqttCommandEntity command) {
	try {
		MqttClient client = MqttClientFactory.getMqttClient(
				command.getUrl(), command.getClientID(), redisTemplate);

		for (String topic : command.getTopic()) {
			client.publish(topic, command.getContent().getBytes(),
					command.getQos(), command.isRetained());
		}
	} catch (MqttException e) {
		e.printStackTrace();
	}
}
 
開發者ID:projectsrepos,項目名稱:jim,代碼行數:19,代碼來源:TestService.java

示例11: process

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
@Override
public void process(Exchange exchange) throws Exception {
    MqttClient client = getEndpoint().getClient();
    String topic = getEndpoint().getTopic();
    
    int qos = exchange.getIn().getHeader(PahoConstants.CAMEL_PAHO_MSG_QOS, getEndpoint().getQos(), Integer.class);
    boolean retained = exchange.getIn().getHeader(PahoConstants.CAMEL_PAHO_MSG_RETAINED, getEndpoint().isRetained(), Boolean.class);
    
    byte[] payload = exchange.getIn().getBody(byte[].class);

    MqttMessage message = new MqttMessage(payload);
    message.setQos(qos);
    message.setRetained(retained);
    client.publish(topic, message);
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:16,代碼來源:PahoProducer.java

示例12: main

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    Properties properties = new Properties();
    properties.load(new FileInputStream("src/main/resources/device.properties"));

    // d:<orgid>:<device-type>:<device-id>
    String clientId = String.format("d:%s:%s:%s",
            properties.getProperty("Org_ID"),
            properties.getProperty("Device_Type"),
            properties.getProperty("Device_ID"));

    // tcp://<Org_ID>.messaging.internetofthings.ibmcloud.com:1883
    String serverUrl = String.format("tcp://%s.messaging.internetofthings.ibmcloud.com:1883", properties.getProperty("Org_ID"));

    // iot-2/evt/<event-id>/fmt/json
    String topic = String.format("iot-2/evt/%s/fmt/json", properties.getProperty("EVENT_ID"));

    String password = properties.getProperty("Authentication_Token");

    MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setUserName(USERNAME);
    connectOptions.setPassword(password.toCharArray());
    MqttClient client = new MqttClient(serverUrl, clientId);
    client.connect(connectOptions);

    // Generate random temperature values between 40 - 60
    Random rand = new Random();

    while (true) {
        int temprature = rand.nextInt((60 - 40) + 1) + 40;
        JsonObject event = new JsonObject();
        event.addProperty("temperature", temprature);
        event.addProperty("timestamp", Instant.now().toEpochMilli());
        System.out.println("Published Message: " + event.toString());
        client.publish(topic, new MqttMessage(event.toString().getBytes(StandardCharsets.UTF_8)));
        try {
            Thread.sleep(500);
        } catch (Exception ex) {

        }
    }
}
 
開發者ID:pkhanal,項目名稱:flink-watson-iot-connector,代碼行數:42,代碼來源:DeviceSimulator.java

示例13: publishBigMessage

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
@Test
public void publishBigMessage(TestContext context) {

  this.async = context.async();

  try {

    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();

    byte[] message = new byte[MQTT_BIG_MESSAGE_SIZE];

    client.publish(MQTT_TOPIC, message, 0, false);

    context.assertTrue(true);

  } catch (MqttException e) {

    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
開發者ID:vert-x3,項目名稱:vertx-mqtt,代碼行數:24,代碼來源:MqttServerMaxMessageSizeTest.java

示例14: publish

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
private void publish(TestContext context, String topic, String message, int qos) {

    this.async = context.async();

    try {
      MemoryPersistence persistence = new MemoryPersistence();
      MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
      client.connect();

      client.publish(topic, message.getBytes(), qos, false);

      this.async.await();

      context.assertTrue(true);

    } catch (MqttException e) {

      context.assertTrue(false);
      e.printStackTrace();
    }
  }
 
開發者ID:vert-x3,項目名稱:vertx-mqtt,代碼行數:22,代碼來源:MqttServerClientPublishTest.java

示例15: run

import org.eclipse.paho.client.mqttv3.MqttClient; //導入方法依賴的package包/類
public void run(String... args) {
    System.out.println("QoS1Producer initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    if (!host.startsWith("tcp://")) {
        host = "tcp://" + host;
    }

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldQoS1Producer");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());

        // Connect the client
        System.out.println("Connecting to Solace messaging at " + host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Create a Mqtt message
        String content = "Hello world from MQTT!";
        MqttMessage message = new MqttMessage(content.getBytes());
        // Set the QoS on the Messages - 
        // Here we are using QoS of 1 (equivalent to Persistent Messages in Solace)
        message.setQos(1);

        System.out.println("Publishing message: " + content);

        // Publish the message
        mqttClient.publish("Q/tutorial", message);

        // Disconnect the client
        mqttClient.disconnect();

        System.out.println("Message published. Exiting");

        System.exit(0);
    } catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}
 
開發者ID:SolaceSamples,項目名稱:solace-samples-mqtt,代碼行數:52,代碼來源:QoS1Producer.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttClient.publish方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。