当前位置: 代码迷 >> 综合 >> 基于Netty实现Mqtt客户端(二)-使用netty-mqtt-client
  详细解决方案

基于Netty实现Mqtt客户端(二)-使用netty-mqtt-client

热度:26   发布时间:2023-12-13 15:24:06.0

netty-mqtt-client

关于

基于netty实现的mqtt客户端,可用于Java、Android环境。持续开发中,现已完成基本框架及功能,目前仅支持qos1级别通讯,后期根据需要再开发qos2级别。

如何使用

Gradle:

repositories {mavenCentral()
}dependencies {implementation 'io.github.x2ge:netty-mqtt-client:2.0.4'
}

连接

MqttClient mqttClient = new MqttClient();
MqttConnectOptions options = new MqttConnectOptions();
options.setHost("localhost");
options.setPort(1883);
options.setClientIdentifier("netty_mqtt_c1");
options.setUserName("testuser");
options.setPassword("123456".getBytes(StandardCharsets.UTF_8));
options.setKeepAliveTime(10);
options.setCleanSession(true);
// 配置动作超时时间
mqttClient.setActionTimeout(3000);
// 配置掉线重连
mqttClient.setReconnectOnLost(5, 10000);
mqttClient.connect(options);

监听

mqttClient.setCallback(new MqttClient.Callback() {@Overridepublic void onConnected() {// testtry {mqttClient.subscribe("netty_mqtt_c1");mqttClient.subscribe("testtopic/#");mqttClient.publish("netty_mqtt_c1", "hello, netty mqtt!");mqttClient.unsubscribe("netty_mqtt_c1");} catch (Exception e) {e.printStackTrace();}}@Overridepublic void onConnectFailed(Throwable e) {}@Overridepublic void onConnectLost(Throwable e) {}@Overridepublic void onReconnectStart(int cur) {}@Overridepublic void onMessageArrived(String topic, String s) {}
});

订阅

mqttClient.subscribe("netty_mqtt_c1");

取消订阅

mqttClient.unsubscribe("netty_mqtt_c1");

发布消息

mqttClient.publish("netty_mqtt_c1", "hello, netty mqtt!");

关闭连接

mqttClient.close();	

项目源码

netty-mqtt-client

  相关解决方案