代码改变世界

MQTT协议实现Eclipse Paho学习总结二

2015-04-01 15:30  辣椒酱  阅读(2673)  评论(0编辑  收藏  举报

一、概述

前一篇博客(MQTT协议实现Eclipse Paho学习总结一) 写了一些MQTT协议相关的一些概述和其实现Eclipse Paho的报文类别,同时对心跳包进行了分析。这篇文章,在不涉及MQTT逻辑实现的基础之上分析一下Eclipse Paho中Socket通信的实现,这里我们主要阐述其采用Java同步技术将同步的Socket通信异步化的过程。

二、上菜

先看一下在org.eclipse.paho.client.mqttv3.internal有两个类,CommsSender,CommsReceiver,通过名字我们知道这个这两个类是关于客户端发送消息和接收消息的两个类。上源码分析。

2.1 CommsSender

我们先来看一下CommsSender的run方法。
  1. public void run() {  
  2.         final String methodName = "run";  
  3.         MqttWireMessage message = null;  
  4.         while (running && (out != null)) {//超级无限循环  
  5.             try {  
  6.                 message = clientState.get();//主要看这里获取message时进行了阻塞,即clientState.get()方法没有获得消息的时候,代码一直处理阻塞状态,不会一直无限循环!  
  7.                 if (message != null) {  
  8.                     //@TRACE 802=network send key={0} msg={1}  
  9.                     log.fine(className,methodName,"802"new Object[] {message.getKey(),message});  
  10.   
  11.                     if (message instanceof MqttAck) {  
  12.                         out.write(message);  
  13.                         out.flush();  
  14.                     } else {  
  15.                         MqttToken token = tokenStore.getToken(message);  
  16.                         // While quiescing the tokenstore can be cleared so need   
  17.                         // to check for null for the case where clear occurs  
  18.                         // while trying to send a message.  
  19.                         if (token != null) {  
  20.                             synchronized (token) {//使用了同步,防止一次性多个写操作。  
  21.                                 out.write(message);  
  22.                                 out.flush();  
  23.                                 clientState.notifySent(message);//通知已经发送了一个消息  
  24.                             }  
  25.                         }  
  26.                     }  
  27.                 } else { // null message  
  28.                     //@TRACE 803=get message returned null, stopping}  
  29.                     log.fine(className,methodName,"803");  
  30.   
  31.                     running = false;  
  32.                 }  
  33.             } catch (MqttException me) {  
  34.                 handleRunException(message, me);  
  35.             } catch (Exception ex) {          
  36.                 handleRunException(message, ex);      
  37.             }  
  38.         } // end while  
  39.           
  40.         //@TRACE 805=<  
  41.         log.fine(className, methodName,"805");  
  42.   
  43.     }  
点击message = clientState.get();中get()方法进入之后,方法的部分内容如下:
  1. synchronized (queueLock) {  
  2.             while (result == null) {          
  3.                 if (pendingMessages.isEmpty() && pendingFlows.isEmpty()) {  
  4.                     try {  
  5.                         long ttw = getTimeUntilPing();  
  6.                         //@TRACE 644=nothing to send, wait for {0} ms  
  7.                         log.fine(className,methodName, "644"new Object[] {new Long(ttw)});                          
  8.    
  9.                         queueLock.wait(getTimeUntilPing());//如果pendingMessages队列和pendingFlows队列为空,则放弃queueLock锁,等待,而这个等待时间是有限的,如果长时间没有发送消息,同时等待的时间超过了心跳包发送的时间,那么就往下执行,根据实际情况发送心跳包或者消息。  
  10.                     } catch (InterruptedException e) {  
  11.                     }  
  12.                 }  
ClientState中还有一个send()方法,部分内容如下:
  1. if (message instanceof MqttPublish) {  
  2.             synchronized (queueLock) {  
  3.                 if (actualInFlight >= this.maxInflight) {  
  4.                     //@TRACE 613= sending {0} msgs at max inflight window  
  5.                     log.fine(className, methodName, "613"new Object[]{new Integer(actualInFlight)});  
  6.   
  7.                     throw new MqttException(MqttException.REASON_CODE_MAX_INFLIGHT);  
  8.                 }  
  9.                   
  10.                 MqttMessage innerMessage = ((MqttPublish) message).getMessage();  
  11.                 //@TRACE 628=pending publish key={0} qos={1} message={2}  
  12.                 log.fine(className,methodName,"628"new Object[]{new Integer(message.getMessageId()), new Integer(innerMessage.getQos()), message});  
  13.   
  14.                 switch(innerMessage.getQos()) {  
  15.                     case 2:  
  16.                         outboundQoS2.put(new Integer(message.getMessageId()), message);  
  17.                         persistence.put(getSendPersistenceKey(message), (MqttPublish) message);  
  18.                         break;  
  19.                     case 1:  
  20.                         outboundQoS1.put(new Integer(message.getMessageId()), message);  
  21.                         persistence.put(getSendPersistenceKey(message), (MqttPublish) message);  
  22.                         break;  
  23.                 }  
  24.                 tokenStore.saveToken(token, message);  
  25.                 pendingMessages.addElement(message);  
  26.                 queueLock.notifyAll();//通知get方法,我已经有消息放入队列了!!!  
  27.             }  
总 的过程如下:send方法将消息放入到pendingMessages队列和pendingFlows当中同时发送消息唤醒等待中的线程,get等待 pendingMessages队列和pendingFlows中的消息,同时等待唤醒,如果有消息放入,同时被唤醒,那么就执行发送消息的操作。这个过 程是不是跟操作系统当中的生产者-消费者的关系一样呢!!!
 

2.2 CommsReceiver

 
再来看一下CommsReceiver的run()方法
  1. public void run() {  
  2.         final String methodName = "run";  
  3.         MqttToken token = null;  
  4.         //在这里,因为客户端无法判断,服务器什么时候能够发消息过来,因此只能采用无限循环的方式,不断的去判断是否有新消息发送过来。  
  5.         while (running && (in != null)) {//超级无限循环  
  6.             try {  
  7.                 //@TRACE 852=network read message  
  8.                 log.fine(className,methodName,"852");  
  9.                 MqttWireMessage message = in.readMqttWireMessage();// 这里,因为socket.getInputStream()一直在阻塞,如果没有消息是读不到message的,因此在这里的while循环也没有无限制 的运行下去,只有在有消息的时候才往下走。socket默认是阻塞的,就是在读的时候如果读不到资源就会一直等待,直到超时(如果设置了超时时间的话), 如果服务端和客户端都在读的话而没有写的话就会一直阻塞。你可以使用SocketChannel,设置socket的通道,使其变成非阻塞的。  
  10.                   
  11.                 if (message instanceof MqttAck) {//判断是否是确认包  
  12.                     token = tokenStore.getToken(message);  
  13.                     if (token!=null) {  
  14.                         synchronized (token) {  
  15.                             // Ensure the notify processing is done under a lock on the token  
  16.                             // This ensures that the send processing can complete  before the   
  17.                             // receive processing starts! ( request and ack and ack processing  
  18.                             // can occur before request processing is complete if not!  
  19.                             clientState.notifyReceivedAck((MqttAck)message);  
  20.                         }  
  21.                     } else {  
  22.                         // It its an ack and there is no token then something is not right.  
  23.                         // An ack should always have a token assoicated with it.  
  24.                         throw new MqttException(MqttException.REASON_CODE_UNEXPECTED_ERROR);  
  25.                     }  
  26.                 } else {  
  27.                     // A new message has arrived,一个新消息过来。  
  28.                     clientState.notifyReceivedMsg(message);//点击进入之后  
  29.                 }  
  30.             }  
  31.             catch (MqttException ex) {  
  32.                 //@TRACE 856=Stopping, MQttException  
  33.                 log.fine(className,methodName,"856",null,ex);  
  34.                 running = false;  
  35.                 // Token maybe null but that is handled in shutdown  
  36.                 clientComms.shutdownConnection(token, ex);  
  37.             }   
  38.             catch (IOException ioe) {  
  39.                 //@TRACE 853=Stopping due to IOException  
  40.                 log.fine(className,methodName,"853");  
  41.   
  42.                 running = false;  
  43.                 // An EOFException could be raised if the broker processes the   
  44.                 // DISCONNECT and ends the socket before we complete. As such,  
  45.                 // only shutdown the connection if we're not already shutting down.  
  46.                 if (!clientComms.isDisconnecting()) {  
  47.                     clientComms.shutdownConnection(token, new MqttException(MqttException.REASON_CODE_CONNECTION_LOST, ioe));  
  48.                 } // else {  
  49.             }  
  50.         }  
  51.           
  52.         //@TRACE 854=<  
  53.         log.fine(className,methodName,"854");  
  54.     }  
 
我们点击进入clientState.notifyReceivedMsg(message);方法,部分代码如下:
  1. if (message instanceof MqttPublish) {  
  2.                 MqttPublish send = (MqttPublish) message;  
  3.                 switch (send.getMessage().getQos()) {  
  4.                 case 0:  
  5.                 case 1:  
  6.                     if (callback != null) {  
  7.                         callback.messageArrived(send);  
  8.                     }  
  9.                     break;  
我们点击进入callback.messageArrived(send);方法,
  1. public void messageArrived(MqttPublish sendMessage) {  
  2.         final String methodName = "messageArrived";  
  3.         if (mqttCallback != null) {  
  4.             // If we already have enough messages queued up in memory, wait  
  5.             // until some more queue space becomes available. This helps   
  6.             // the client protect itself from getting flooded by messages   
  7.             // from the server.  
  8.             synchronized (spaceAvailable) {  
  9.                 if (!quiescing && messageQueue.size() >= INBOUND_QUEUE_SIZE) {  
  10.                     try {  
  11.                         // @TRACE 709=wait for spaceAvailable  
  12.                         log.fine(className, methodName, "709");  
  13.                         spaceAvailable.wait();  
  14.                     } catch (InterruptedException ex) {  
  15.                     }  
  16.                 }  
  17.             }  
  18.             if (!quiescing) {  
  19.                 messageQueue.addElement(sendMessage);  
  20.                 // Notify the CommsCallback thread that there's work to do...  
  21.                 synchronized (workAvailable) {  
  22.                     // @TRACE 710=new msg avail, notify workAvailable  
  23.                     log.fine(className, methodName, "710");  
  24.                     workAvailable.notifyAll();  
  25.                 }  
  26.             }  
  27.         }  
  28.     }  
在 这里,同样使用了生产者-消费者模式,在run方法里,我们可以看到其调用了handleMessage,在这个方法里面调用了 mqttCallback.messageArrived(destName, publishMessage.getMessage());接口回调。