Mqtt_Java_IDEA中编写“发布者”和“订阅者”

1Java创建项目

2导入依赖

将下面Mqtt的库名复制到      <dependencies>    下面

<dependency>
      <groupId>org.eclipse.paho</groupId>
      <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
      <version>1.2.5</version>
    </dependency>

复制后

复制完右上会有如图标志点击加载他会自动下载依赖

下载完成后可以看到库了

3编写订阅者

package org.example;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

//订阅者
public class SubClient {

    public static void main(String[] args) throws MqttException {
        //创建客户端对象
        MqttClient client= new MqttClient("tcp://127.0.0.1:1883","li-Mqtt-1",new MemoryPersistence());
        //创建连接配置
        MqttConnectOptions options=new MqttConnectOptions();
        options.setCleanSession(true);

        //将配置设置给客户端
        client.connect(options);
        //配置回调函数,等待信息
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {
                System.out.println("连接断开时。。。"+throwable.getMessage());
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("接收信息....主题为:"+s+"---信息为:"+new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("信息传递完成。。。。"+iMqttDeliveryToken.isComplete());
            }
        });

        //开始订阅
        client.subscribe("wd");
        System.out.println("订阅已经准备好了");
    }
}

4编写发布者

package org.example;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;

//消息发布者
public class PubClient {

    public static void main(String[] args) throws MqttException {
        //创建客户端对象
        MqttClient client=new MqttClient("tcp://127.0.0.1:1883","li-Mqtt-2",new MemoryPersistence());
        //创建连接配置
        MqttConnectOptions options=new MqttConnectOptions();
        options.setCleanSession(true);

        //将配置设置给客户端
        client.connect(options);
        //创建消息对象
        MqttMessage mqttMessage=new MqttMessage("我是消息".getBytes(StandardCharsets.UTF_8));
        //设置消息等级
        mqttMessage.setQos(2);
        //发布消息
        client.publish("wd",mqttMessage);
        //断开连接
        client.disconnect();
        //关闭Mqtt客户端
        client.close();
    }
}

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值