答案 0 :(得分:1)
MQTT通常使用TCP作为底层协议(仅在websocket上下文中使用HTTP)。
使用paho mqtt客户端库的用法连接mqtt客户端的Java示例:
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
...
final MqttClient mqttClient = new MqttClient("tcp://localhost:1883",
MqttClient.generateClientId(),
new MemoryPersistence());
opt.setUserName("User");
...
mqttClient.connect(opt);
...
//subscribe to all topics
mqttClient.subscribe("#");
//publish your status ON with a QoS 1 message that is retained
mqttClient.publish("cmnd/power, ("on").getBytes(), 1, true);
答案 1 :(得分:0)
首先,您需要建立mqtt连接,一旦连接成功,您可以将任何有效负载发送到所需的主题。 这就是您需要启动连接的方式。
String clientId = MqttClient.generateClientId();
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("USERNAME");
options.setPassword("PASSWORD".toCharArray());
MqttAndroidClient client =
new MqttAndroidClient(this.getApplicationContext(), "tcp://broker.hivemq.com:1883",
clientId);
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG, "onSuccess");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG, "onFailure");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
You can publish message to topic power
String topic = "power";
String payload = "ON";
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
client.publish(topic, message);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}