MQTT com Java示例

MQTT(消息队列遥测传输)和简单易用的协议,物联网解决方案(Internet das coisas),邮件解决方案的质量保证,代理人和代理人,ja que esadas罗布斯托。

MQTTéumpadrão 发布/订阅,代理服务商(经纪人)收货,作为Mensagens e Distribui Param tem Interessem。 客户关系管理专家,客户关系管理专家。

MQTT的功能说明

依赖关系

Háapenasumadependênciapara o projeto,客户Paho para o MQTT,desenvolvido pela Eclipse,que pode ser baixado aqui: https ://www.eclipse.org/paho/clients/java/。

班级

作为需要执行的类的必要类的主菜单:主,类的主要负责人,作为客户的委托人,客户MQTT,公共服务,公共服务,客户不断增加的存储空间不会导致误报。

Main.java

package javamqtt ;

import java . text . SimpleDateFormat ;

public class Main {

    public static void main ( String [] args ) throws InterruptedException {
        ClienteMQTT clienteMQTT = new ClienteMQTT ( "tcp://broker.mqttdashboard.com:1883" , null , null );
        clienteMQTT . iniciar ();

        new Ouvinte ( clienteMQTT , "br/com/paulocollares/#" , 0 );

        while ( true ) {
            Thread . sleep ( 1000 );
            String mensagem = "Mensagem enviada em " + new SimpleDateFormat ( "dd/MM/yyyy HH:mm:ss" ). format ( System . currentTimeMillis ()) + " - Teste de MQTT disponivel em www.paulocollares.com.br" ;

            clienteMQTT . publicar ( "br/com/paulocollares/teste" , mensagem . getBytes (), 0 );
        }
    }
}

ClienteMQTT.java

package javamqtt ;

import java . util . Arrays ;
import org . eclipse . paho . client . mqttv3 . IMqttDeliveryToken ;
import org . eclipse . paho . client . mqttv3 . IMqttMessageListener ;
import org . eclipse . paho . client . mqttv3 . IMqttToken ;
import org . eclipse . paho . client . mqttv3 . MqttCallbackExtended ;
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 . MqttDefaultFilePersistence ;

public class ClienteMQTT implements MqttCallbackExtended {

    private final String serverURI ;
    private MqttClient client ;
    private final MqttConnectOptions mqttOptions ;

    public ClienteMQTT ( String serverURI , String usuario , String senha ) {
        this . serverURI = serverURI ;

        mqttOptions = new MqttConnectOptions ();
        mqttOptions . setMaxInflight ( 200 );
        mqttOptions . setConnectionTimeout ( 3 );
        mqttOptions . setKeepAliveInterval ( 10 );
        mqttOptions . setAutomaticReconnect ( true );
        mqttOptions . setCleanSession ( false );

        if ( usuario != null && senha != null) {
            mqttOptions . setUserName ( usuario );
            mqttOptions . setPassword ( senha . toCharArray ());
        }
    }

    public IMqttToken subscribe ( int qos , IMqttMessageListener gestorMensagemMQTT , String ... topicos ) {
        if ( client == null || topicos . length == 0 ) {
            return null ;
        }
        int tamanho = topicos . length ;
        int [] qoss = new int [ tamanho ];
        IMqttMessageListener [] listners = new IMqttMessageListener [ tamanho ];

        for ( int i = 0 ; i < tamanho ; i ++) {
            qoss [ i ] = qos ;
            listners [ i ] = gestorMensagemMQTT ;
        }
        try {
            return client . subscribeWithResponse ( topicos , qoss , listners );
        } catch ( MqttException ex ) {
            System . out . println ( String . format ( "Erro ao se inscrever nos tópicos %s - %s" , Arrays . asList ( topicos ), ex ));
            return null ;
        }
    }

    public void unsubscribe ( String ... topicos ) {
        if ( client == null || !client.isConnected() || topicos.length == 0) {
            return ;
        }
        try {
            client . unsubscribe ( topicos );
        } catch ( MqttException ex ) {
            System . out . println ( String . format ( "Erro ao se desinscrever no tópico %s - %s" , Arrays . asList ( topicos ), ex ));
        }
    }

    public void iniciar () {
        try {
            System . out . println ( "Conectando no broker MQTT em " + serverURI );
            client = new MqttClient ( serverURI , String . format ( "cliente_java_%d" , System . currentTimeMillis ()), new MqttDefaultFilePersistence ( System . getProperty ( "java.io.tmpdir" )));
            client . setCallback ( this );
            client . connect ( mqttOptions );
        } catch ( MqttException ex ) {
            System . out . println ( "Erro ao se conectar ao broker mqtt " + serverURI + " - " + ex );
        }
    }

    public void finalizar () {
        if ( client == null || !client.isConnected()) {
            return ;
        }
        try {
            client . disconnect ();
            client . close ();
        } catch ( MqttException ex ) {
            System . out . println ( "Erro ao desconectar do broker mqtt - " + ex );
        }
    }

    public void publicar ( String topic , byte [] payload , int qos ) {
        publicar ( topic , payload , qos , false );
    }

    public synchronized void publicar ( String topic , byte [] payload , int qos , boolean retained ) {
        try {
            if ( client . isConnected ()) {
                client . publish ( topic , payload , qos , retained );
                System . out . println ( String . format ( "Tópico %s publicado. %dB" , topic , payload . length ));
            } else {
                System . out . println ( "Cliente desconectado, não foi possível publicar o tópico " + topic );
            }
        } catch ( MqttException ex ) {
            System . out . println ( "Erro ao publicar " + topic + " - " + ex );
        }
    }

    @ Override
    public void connectionLost ( Throwable thrwbl ) {
        System . out . println ( "Conexão com o broker perdida -" + thrwbl );
    }

    @ Override
    public void connectComplete ( boolean reconnect , String serverURI ) {
        System . out . println ( "Cliente MQTT " + ( reconnect ? "reconectado" : "conectado" ) + " com o broker " + serverURI );
    }

    @ Override
    public void deliveryComplete ( IMqttDeliveryToken imdt ) {
    }

    @ Override
    public void messageArrived ( String topic , MqttMessage mm ) throws Exception {
    }

}

Ouvinte.java

package javamqtt ;

import org . eclipse . paho . client . mqttv3 . IMqttMessageListener ;
import org . eclipse . paho . client . mqttv3 . MqttMessage ;

public class Ouvinte implements IMqttMessageListener {

    public Ouvinte ( ClienteMQTT clienteMQTT , String topico , int qos ) {
        clienteMQTT . subscribe ( qos , this , topico );
    }

    @ Override
    public void messageArrived ( String topico , MqttMessage mm ) throws Exception {
        System . out . println ( "Mensagem recebida:" );
        System . out . println ( " \t Tópico: " + topico );
        System . out . println ( " \t Mensagem: " + new String ( mm . getPayload ()));
        System . out . println ( "" );
    }

}

经纪商MQTT gratuitos epúblicospara teste

没有证人公开身份证明的经验,没有公开发行证明的权利,没有公开证明的权利。 推荐给我们的项目,推荐 Mosquitto或Eclipse。

百老汇

GitHub上的示例程序: https : //github.com/pcollares/exemplos-blog/tree/master/JavaMQTT

[]的

From: https://dev.to/pcollares/exemplo-de-uso-do-mqtt-com-java-mgo

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值