android MQTT的简单使用

本文介绍了如何在Windows 10上安装和配置mosquitto服务,并通过命令行验证其运行状态。同时,讲解了Android应用中集成MQTT客户端库Paho的步骤,包括添加依赖、设置权限及实现消息的发送与接收。最后,提供了mosquitto配置文件的修改建议,以确保Android设备与服务器在同一局域网内可以顺利通信。
摘要由CSDN通过智能技术生成

一.windows10 安装mosquitto服务

官网下载地址 "http://www.eclipse.org/paho/components/tool/",下载windows 版本后安装,最好是配置一下环境变量。安装成功之后可以在 任务管理器-服务 界面看到mosquitto。

cmd 以管理员权限打开命令行窗口1, 打开mosquitto服务    "net start mosquitto"

cmd 以管理员权限打开命令行窗口2, 订阅主题 test      "mosquitto_sub -t  test"

cmd 以管理员权限打开命令行窗口3, 发布主题为 test 的消息     "mosquitto_pub -t  test -m "haha" ",此时如果命令行窗口能收到 消息"haha",证明本地mosquitto 服务器已配置并启动成功。

关闭mosquitto服务的命令为    "net stop  mosquitto"

二. Android 使用mqtt

1.在bulid.gradle(:app) 文件中添加依赖包

implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'

2.添加权限 

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

3.直接贴代码

public class MQtt{

    public String TOPIC1 = "test/1";
    private MqttConnectOptions options;
    private String clientId = "123456";
    private String HOST = "tcp://192.128.0.127:1883"; //本地ipv4
    private MqttClient client;
    private static final int QOS0 = 0;//只发送一次 可能会丢失
    private static final int QOS1 = 1;//至少会收到一次  可能会重复
    private static final int QOS2 = 2;//保证会收到一次

    private String userName = "test001"; //非必须
    private String password = "123456"; //非必须

    private IMqttCallBack callBack;

    private static final MQtt mQtt = new MQtt();
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    public static MQtt getInstance(){
        return mQtt;
    }

    private void initMQTTClient(){
        try{
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //host为主机名,clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表
            client = new MqttClient(HOST, clientId, new MemoryPersistence());
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //options.setWill(myTopic,null,2,false); //遗嘱   断开连接时,会发送一条信息
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(password.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            options.setKeepAliveInterval(60);
            //设置回调
            client.setCallback(mqttCallBack);
        }catch(Exception e){
            e.printStackTrace();
            AppLogger.e(e.getMessage());
        }
    }

    /**
     * mqtt 请求回调
     */
    private final MqttCallbackExtended mqttCallBack = new MqttCallbackExtended(){
        @Override
        public void connectComplete(boolean reconnect, String serverURI){
            subscribeTopic();
        }

        @Override
        public void connectionLost(Throwable cause){
            //连接丢失后,一般在这里面进行重连
            startReconnect();
            AppLogger.e("connectionLost");
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token){
            //publish后会执行到这里
            AppLogger.e("deliveryComplete");
            App.showMessage("发送成功");
        }

        @Override
        public void messageArrived(String topicName, MqttMessage message){
            byte[] realMessage = message.getPayload();
            if(realMessage.length > 0){
                String result = new String(message.getPayload());
                AppLogger.e("messageArrived", result);
                // subscribe后得到的消息会执行到这里面
                if(callBack != null){
                    callBack.onReceiver(result);
                }
            }
        }
    };

    /**
     * 断开连接
     */
    private void interrupterConnect(){
        try{
            if(client != null && client.isConnected()){
                client.disconnect();
            }
        }catch(MqttException e){
            e.printStackTrace();
        }
    }

    /**
     * 连接服务器
     */
    private void connectService(){
        try{
            if(!client.isConnected()){
                client.connect(options);
            }
        }catch(Exception e){
            AppLogger.e(e.getMessage());
            App.showMessage(e.getMessage());
        }
    }

    /**
     * 订阅主题
     */
    private void subscribeTopic(){
        try{
            if(client.isConnected()){
                int[] Qos = {QOS2};
                String[] topic1 = {TOPIC1};
                client.subscribe(topic1, Qos);
                AppLogger.e("连接成功");
                App.showMessage("连接成功");
            }else{
                App.showMessage("连接失败");
            }
        }catch(Exception e){
            e.printStackTrace();
            AppLogger.e(e.getMessage());
            App.showMessage(e.getMessage());
        }
    }

    /**
     * 连接服务器
     */
    public void bindService(IMqttCallBack callBack, String host, String port, String topic){
        interrupterConnect();
        this.callBack = callBack;
        this.HOST = host + ":" + port;
        this.TOPIC1 = topic;
        initMQTTClient();
        executorService.execute(() -> {
            connectService();
        });
    }

    /**
     * 发送消息
     *
     * @param msg   消息
     * @param topic 主题
     */
    public void sendMsg(String msg, String topic){
        MqttMessage message = new MqttMessage();
        message.setPayload(msg.getBytes());
        message.setQos(QOS2);
        message.setRetained(false);
        try{
            if(client != null && client.isConnected()){
                client.publish(topic, message);
            }
        }catch(MqttException e){
            e.printStackTrace();
            AppLogger.e(e.getMessage());
            App.showMessage(e.getMessage());
        }
    }

    /**
     * 取消连接
     */
    public void disconnect(){
        try{
            client.disconnect();
        }catch(MqttException e){
            AppLogger.e(e.getMessage());
            App.showMessage(e.getMessage());
        }
    }

    /**
     * 重连
     */
    private void startReconnect(){
        executorService.execute(this::connectService);
    }

}

4.在mosquitto 安装目录下,打开mosquitto.conf 文件,增加以下配置,重启mosquitto, 关闭电脑防火墙,android 手机和电脑在用一个局域网下即可互相通信。

allow_anonymous true #允許匿名
port 1883 #mqtt端口

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值