gpt4 book ai didi

java - 我如何将带有用户名和密码的 Java mqtt 客户端连接到 emqttd(EMQ) 代理?

转载 作者:行者123 更新时间:2023-11-30 06:43:54 29 4
gpt4 key购买 nike

我可以使用此 Java 代码订阅 mosquitto 代理,无需用户名和密码。现在,我想订阅一个需要一些虚拟用户名和密码的 emqttd 代理。我怎样才能做到这一点?。谢谢。

http://tgrall.github.io/blog/2017/01/02/getting-started-with-mqtt/#disqus_thread

https://github.com/emqtt/emqttd

package com.mapr.demo.mqtt.simple;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;

public class Subscriber {

public static void main(String[] args) throws MqttException {

System.out.println("== START SUBSCRIBER ==");

MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
client.setCallback( new SimpleMqttCallBack() );
client.connect();

client.subscribe("iot_data");

}

}

最佳答案

您可以使用 MqttConnectOptions :

 public class Subscriber {

private static final String CONNECTION_URL = "tcp://localhost:1883";
private static final String SUBSCRIPTION = "iot_data";
private static final String USERNAME = "username";
private static final String PASSWORD = "top-secret";


public static void main(String[] args) throws MqttException {

System.out.println("== START SUBSCRIBER ==");

MqttClient client = new MqttClient(CONNECTION_URL,
MqttClient.generateClientId());

MqttConnectOptions connOpts = setUpConnectionOptions(USERNAME, PASSWORD);
client.connect(connOpts);

client.subscribe(SUBSCRIPTION);

}

private static MqttConnectOptions setUpConnectionOptions(String username, String password) {
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(username);
connOpts.setPassword(password.toCharArray());
return connOpts;
}

}

关于java - 我如何将带有用户名和密码的 Java mqtt 客户端连接到 emqttd(EMQ) 代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51626898/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com