2020-05-04 結(jié)合Netty和moquette模擬MQTT發(fā)布客戶端

模擬MQTT發(fā)布客戶端

上代碼:
1.pubClient

package com.MyMQTTServerAndClient.publishClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import org.eclipse.moquette.parser.netty.MQTTDecoder;
import org.eclipse.moquette.parser.netty.MQTTEncoder;
public class pubClient {
    public static void main(String[] args) {
        pubClient.startMqttClient();
    }
    public static void startMqttClient(){
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast("log", new LoggingHandler());
                    pipeline.addLast("decoder", new MQTTDecoder());//解碼
                    pipeline.addLast("encoder", new MQTTEncoder());//編碼
                    pipeline.addLast("handler", new PubMQTTClientHandler());
                }
            });
            ChannelFuture ch = b.connect("127.0.0.1", 7777).sync();
            ch.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            group.shutdownGracefully();
        }
    }
}

2.PubMQTTClientHandler

package com.MyMQTTServerAndClient.publishClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;
import org.eclipse.moquette.proto.messages.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.IntStream;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
 * 暫時只支持Qos【0,1】
 * 備注:qos=0情況下服務端接收到數(shù)據(jù)后MessageID會被設置為null【應該是編解碼的時候被設置】
 * 該類負責發(fā)布話題
 */
public class PubMQTTClientHandler extends SimpleChannelInboundHandler<AbstractMessage> {

    private static Logger logger = LoggerFactory.getLogger(PubMQTTClientHandler.class);

    private String userName="admin";

    private String passWord="password";

    ScheduledFuture<?> scheduledFuture;//取消客戶端心跳用

    private static AtomicBoolean firstPingResp=new AtomicBoolean(true);//第一次ping通
    //Qos=0的待發(fā)布的話題
    LinkedBlockingDeque<PublishMessage> zeroQosPubQueue=new LinkedBlockingDeque<>();
    //Qos=1的待發(fā)布的話題
    LinkedBlockingDeque<PublishMessage> oneQosPubQueue=new LinkedBlockingDeque<>();
    //Qos=1的發(fā)布話題的ack
    LinkedBlockingDeque<PubAckMessage> oneQosPubAckQueue=new LinkedBlockingDeque<>();
    //已經(jīng)發(fā)送的topic key為messageId value為該PublishMessage
    ConcurrentHashMap<Integer,PublishMessage> alreadySendMap=new ConcurrentHashMap<>();

    ExecutorService executorService;

    CountDownLatch countDownLatch=new CountDownLatch(1);

    List<java.util.concurrent.Future> FutureList=new ArrayList<>();

    private Channel channel;

    private Boolean running=new Boolean(true);

    public PubMQTTClientHandler() {
        executorService= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        //發(fā)布Qos=0的話題
        java.util.concurrent.Future<?> future1 = executorService.submit(() -> {
            while(running){
                while (!zeroQosPubQueue.isEmpty()) {
                    PublishMessage publishMessage = zeroQosPubQueue.removeFirst();
                    channel.writeAndFlush(publishMessage);
                    logger.info("publishMessage {} publish success {}", publishMessage.getTopicName(),publishMessage.getMessageID());
                }
                try {
                    //防止執(zhí)行過快
                    countDownLatch.await(1000, MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //發(fā)布Qos=1的話題
        java.util.concurrent.Future<?> future2 = executorService.submit(() -> {
            while(running){
                while (!oneQosPubQueue.isEmpty()) {
                    PublishMessage publishMessage = oneQosPubQueue.removeFirst();
                    Integer messageID = publishMessage.getMessageID();
                    //還沒發(fā)送過該topic消息,需要加入map
                    if (!alreadySendMap.containsKey(messageID)) {
                        alreadySendMap.put(messageID, publishMessage);
                    }
                    channel.writeAndFlush(publishMessage);
                    logger.info("publishMessage {} publish success {}", publishMessage.getTopicName(),publishMessage.getMessageID());
                    oneQosPubQueue.addLast(publishMessage);
                    try {
                        //防止發(fā)送過快
                        SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //接受Qos=1的話題的ack
        java.util.concurrent.Future<?> future3 = executorService.submit(() -> {
            while(running){
                while (!oneQosPubAckQueue.isEmpty()) {
                    PubAckMessage pubAckMessage = oneQosPubAckQueue.removeFirst();
                    if (alreadySendMap.containsKey(pubAckMessage.getMessageID())) {
                        //topic收到ack贰健,需要從發(fā)送隊列移除該topic
                        oneQosPubQueue.remove(alreadySendMap.get(pubAckMessage.getMessageID()));
                        alreadySendMap.remove(pubAckMessage.getMessageID());
                    } else {
                        logger.error("receive error PubAckMessage {}",
                                pubAckMessage.getMessageID());
                    }
                }
                try {
                    //防止運行過快
                    SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        FutureList.add(future1);
        FutureList.add(future2);
        FutureList.add(future3);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("error message {}",cause);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("client "+ctx.channel().remoteAddress()+" active");
        //連接
        ConnectMessage connectMessage = new ConnectMessage();
        connectMessage.setProcotolVersion((byte) 3);
        connectMessage.setQos(AbstractMessage.QOSType.LEAST_ONE);
        connectMessage.setCleanSession(true);
        connectMessage.setClientID(String.valueOf(UUID.randomUUID()));
        connectMessage.setKeepAlive(60);
        connectMessage.setWillFlag(false);
        connectMessage.setUserFlag(true);
        connectMessage.setUsername(this.userName);
        connectMessage.setPasswordFlag(true);
        connectMessage.setPassword(this.passWord);
        ctx.writeAndFlush(connectMessage,ctx.newPromise().addListener((future)->{
            if(future.cause()==null){
               logger.info("send connectMessage success");
            }else{
               logger.error("send connectMessage error "+future.cause());
            }
        }));

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.error("channelInactive " +ctx.channel().remoteAddress());
        boolean cancel = scheduledFuture.cancel(true);
        logger.info("{} client canal heart beat {}",ctx.channel().localAddress(),cancel);
        ctx.close(ctx.newPromise().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                logger.info("channel {} close ",ctx.channel().localAddress());
            }
        }));
        if(this.channel!=null){
            channel=null;
        }
        //
        running=false;
        //
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AbstractMessage msg) throws Exception {

        if(msg instanceof AbstractMessage){
            byte messageType = msg.getMessageType();
            switch(messageType){
                case AbstractMessage.CONNACK:
                    processConnectAckResp(ctx,msg);
                    break;
                case AbstractMessage.PINGRESP:
                    processPingResp();
                    break;
                case AbstractMessage.PUBACK:
                    processPubAck(ctx,msg);
                    break;
                default:
                    logger.info("message type "+((AbstractMessage) msg).getMessageType());
                    break;
            }
        }
    }

    /**
     * 發(fā)布的topic Qos=1時會收到pubAck
     * @param ctx
     * @param msg
     */
    private void processPubAck(ChannelHandlerContext ctx, AbstractMessage msg) {
        PubAckMessage pubAckMessage = (PubAckMessage) msg;
        boolean result = oneQosPubAckQueue.offerLast(pubAckMessage);
        if(result==true){
            logger.info("receive PubAckMessage {} from MQTTServer,and insert queue success",pubAckMessage.getMessageID());
        }else{
            logger.error("failed insert PubAckMessage {} into queue",pubAckMessage.getMessageID());
        }
    }

    //第一次接收到服務端pingResp后才會發(fā)布主題
    private void processPingResp() {
        if(firstPingResp.get()){
//            IntStream.rangeClosed(5,200).forEach((i)->{
////                publishTopic("mqttClient/topicOne"+i,AbstractMessage.QOSType.LEAST_ONE);
////            });
            publishTopic("mqttClient/topicOne1",AbstractMessage.QOSType.LEAST_ONE);
            publishTopic("mqttClient/topicOne2",AbstractMessage.QOSType.LEAST_ONE);
            publishTopic("mqttClient/topicTwo2",AbstractMessage.QOSType.LEAST_ONE);
            publishTopic("mqttClient/topicTwo3",AbstractMessage.QOSType.MOST_ONE);
            for(int i=0;i<5;i++){
                publishTopic("mqttClient/topicTwo4",AbstractMessage.QOSType.MOST_ONE);
            }
            logger.debug("first receive ping response , start publish topic" );
            firstPingResp.set(false);
        }else{
            logger.debug("ping response");
        }
    }

    /**
     * 發(fā)布主題【Qos目前只支持0络断、1】
     * @param topic
     * @param qos
     */
    private void publishTopic(String topic,AbstractMessage.QOSType qos) {
        //這個字段需要設置,否者無法發(fā)送消息
        PublishMessage publishMessage = new PublishMessage();
        publishMessage.setTopicName(topic);
        publishMessage.setQos(qos);
        int random = new Random().nextInt(10000);//<2^32-1
        /**
         *   qos=0情況下服務端接收到數(shù)據(jù)后MessageID會被設置為null【應該是編解碼的時候被設置】
         */
        publishMessage.setMessageID(random);
        publishMessage.setRetainFlag(false);
        publishMessage.setPayload(ByteBuffer.wrap("I am payload".getBytes()));
        if(qos== AbstractMessage.QOSType.MOST_ONE){
            boolean offer = zeroQosPubQueue.offer(publishMessage);
            if(offer){
                logger.info("publishMessage {} insert zeroQosPubQueue success ",publishMessage.getTopicName());
            }
        }else if(qos== AbstractMessage.QOSType.LEAST_ONE){
            boolean offer = oneQosPubQueue.offer(publishMessage);
            if(offer){
                logger.info("publishMessage {} insert oneQosPubQueue success ",publishMessage.getTopicName());
            }
        }
    }

    private void processConnectAckResp(ChannelHandlerContext ctx, Object msg) {
        ConnAckMessage ackMessage = (ConnAckMessage) msg;
        if(ackMessage.getReturnCode()==(byte)0){
            channel=ctx.channel();
            logger.info("get connectAck success, start heart beat" );
            //存
//            ctx.channel().attr(MyConstants.pingKey).setIfAbsent("firstPing");
            // 定時心跳任務
            scheduledFuture = ctx.channel().eventLoop().scheduleAtFixedRate(() -> {
                PingReqMessage pingReqMessage = new PingReqMessage();
                pingReqMessage.setQos(AbstractMessage.QOSType.MOST_ONE);//心跳暫時MOST_ONE(0)
                ctx.writeAndFlush(pingReqMessage, ctx.newPromise().addListener((future) -> {
                    if (future.cause() == null) {
                        logger.info("send heartBeat success");
                    } else {
                        logger.error("send heartBeat error");
                    }
                }));
            }, 2, 55, SECONDS);
        }else if(ackMessage.getReturnCode()==(byte)4){
            logger.error("get connectAck failed, cannot heart beat,username or password" );//
            ctx.close();
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       ctx.fireUserEventTriggered(evt);
    }
}

下一篇:測試
http://www.reibang.com/p/3f2d9ccfe310

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末答捕,一起剝皮案震驚了整個濱河市祷肯,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌国拇,老刑警劉巖昙篙,帶你破解...
    沈念sama閱讀 211,042評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件秘豹,死亡現(xiàn)場離奇詭異携御,居然都是意外死亡,警方通過查閱死者的電腦和手機既绕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評論 2 384
  • 文/潘曉璐 我一進店門啄刹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人凄贩,你說我怎么就攤上這事誓军。” “怎么了疲扎?”我有些...
    開封第一講書人閱讀 156,674評論 0 345
  • 文/不壞的土叔 我叫張陵昵时,是天一觀的道長。 經(jīng)常有香客問我椒丧,道長壹甥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,340評論 1 283
  • 正文 為了忘掉前任壶熏,我火速辦了婚禮句柠,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘棒假。我一直安慰自己溯职,他們只是感情好,可當我...
    茶點故事閱讀 65,404評論 5 384
  • 文/花漫 我一把揭開白布帽哑。 她就那樣靜靜地躺著谜酒,像睡著了一般。 火紅的嫁衣襯著肌膚如雪祝拯。 梳的紋絲不亂的頭發(fā)上甚带,一...
    開封第一講書人閱讀 49,749評論 1 289
  • 那天她肯,我揣著相機與錄音,去河邊找鬼鹰贵。 笑死晴氨,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的碉输。 我是一名探鬼主播籽前,決...
    沈念sama閱讀 38,902評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼敷钾!你這毒婦竟也來了枝哄?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,662評論 0 266
  • 序言:老撾萬榮一對情侶失蹤阻荒,失蹤者是張志新(化名)和其女友劉穎挠锥,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體侨赡,經(jīng)...
    沈念sama閱讀 44,110評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡蓖租,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了羊壹。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蓖宦。...
    茶點故事閱讀 38,577評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖油猫,靈堂內(nèi)的尸體忽然破棺而出稠茂,到底是詐尸還是另有隱情,我是刑警寧澤情妖,帶...
    沈念sama閱讀 34,258評論 4 328
  • 正文 年R本政府宣布睬关,位于F島的核電站,受9級特大地震影響毡证,放射性物質(zhì)發(fā)生泄漏共螺。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,848評論 3 312
  • 文/蒙蒙 一情竹、第九天 我趴在偏房一處隱蔽的房頂上張望藐不。 院中可真熱鬧,春花似錦秦效、人聲如沸雏蛮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽挑秉。三九已至,卻和暖如春苔货,著一層夾襖步出監(jiān)牢的瞬間犀概,已是汗流浹背立哑。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留姻灶,地道東北人铛绰。 一個月前我還...
    沈念sama閱讀 46,271評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像产喉,于是被迫代替她去往敵國和親捂掰。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,452評論 2 348