Smack網(wǎng)絡(luò)層分析

概述

Smack是一個開源的實(shí)現(xiàn)了XMPP協(xié)議的庫,特別是4.1.0版本以后,直接支持Android系統(tǒng),無需再使用以前那個專門針對Android系統(tǒng)的aSmack移植庫了.雖然在移動端上,用XMPP協(xié)議來做IM并不是一個最優(yōu)選擇,市面上這些大公司基本都是用自己定制的私有協(xié)議,沒有采用XMPP協(xié)議的,不過我們可以拋開協(xié)議層面,只分析一下Smack庫在網(wǎng)絡(luò)層的實(shí)現(xiàn),也是有借鑒意義的。

總體結(jié)構(gòu)

network.png

Smack抽象出一個XMPPConnection的概念,要想收發(fā)消息,首先得建立這個connection,而且這種connection是可以由多個實(shí)例的。XMPPConnection只是一個接口,AbstractXMPPConnection實(shí)現(xiàn)了這個接口并加入了login,connect,processStanza等方法。AbstractXMPPConnection有兩個實(shí)現(xiàn)類,XMPPBOSHConnection和XMPPTCPConnection。其中XMPPBOSHConnection是基于Http協(xié)議來實(shí)現(xiàn)的,而XMPPTCPConnection是直接用Socket來實(shí)現(xiàn)的長連接通信,本文分析的也就是XMPPTCPConnection。一個簡單的使用實(shí)例如下:

XMPPTCPConnection con = new XMPPTCPConnection("igniterealtime.org");
  // Connect to the server
  con.connect();
  // Most servers require you to login before performing other tasks.
  con.login("jsmith", "mypass");
  // Start a new conversation with John Doe and send him a message.
  Chat chat = ChatManager.getInstanceFor(con).createChat("jdoe@igniterealtime.org", new MessageListener() {
      public void processMessage(Chat chat, Message message) {
          // Print out any messages we get back to standard out.
          System.out.println("Received message: " + message);
      }
  });
  chat.sendMessage("Howdy!");
  // Disconnect from the server
  con.disconnect();

接口介紹

XMPPConnection這個接口里有幾個主要的方法 :

public void sendStanza(Stanza stanza) throws NotConnectedException, InterruptedException;
public void addConnectionListener(ConnectionListener connectionListener);
public void addPacketInterceptor(StanzaListener packetInterceptor, StanzaFilter packetFilter);
public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter);
public PacketCollector createPacketCollector(StanzaFilter packetFilter);
public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter);
public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter);
  • sendStanza 發(fā)送包到服務(wù)器。在最新版的Smack中,Stanza就是以前版本中的Packet

  • addConnectionListener 添加ConnectionListener到XMPPConnection中。在該Listener中,監(jiān)聽者可以得到連接是否成功建立,連接關(guān)閉,連接異常關(guān)閉,重連是否成功等事件

  • addPacketInterceptor 向Connection中注冊攔截器StanzaListener,所有發(fā)往服務(wù)器的包都會先過一遍攔截器,你可以在攔截器中對這些包進(jìn)行處理;StanzaFilter過濾器可以允許你定制哪些包才需要攔截; StanzaListener和StanzaFilter常常配對使用,代碼中有各種wrapper類(如ListenerWrapper、InterceptorWrapper等),就是把這兩個接口組合在一個類中,一個負(fù)責(zé)過濾包,一個負(fù)責(zé)實(shí)際處理包

  • addPacketSendingListener 注冊一個Listener,當(dāng)把包通過Socket寫出去后,會回調(diào)這個Listener告知正在發(fā)送狀態(tài)

  • createPacketCollector 當(dāng)你想接收某種類型的包時,可以新建一個包收集器。和StanzaListener不同,包收集器是阻塞式的,直到指定的包收到或者出現(xiàn)超時(我們可以設(shè)置等待一個包的最大時間)等異常

PacketCollector messageCollector = connection.createPacketCollector(messageFilter);
        try {
            connection.createPacketCollectorAndSend(request).nextResultOrThrow();
            // Collect the received offline messages
            Message message = messageCollector.nextResult();
            while (message != null) {
                messages.add(message);
                message = messageCollector.nextResult();
            }
        }
        finally {
            // Stop queuing offline messages
            messageCollector.cancel();
        }
        return messages;
  • addAsyncStanzaListener和addSyncStanzaListener 添加處理收到的包的回調(diào)接口;其中一個叫同步一個叫異步區(qū)別在于,執(zhí)行回調(diào)方法所用的線程池不一樣,其中異步用的是Executors.newCachedThreadPool,而同步用的是一個Executors.newSingleThreadExecutor,可以保證執(zhí)行順序
// First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
        // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
        // their own thread.
        final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
        synchronized (asyncRecvListeners) {
            for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
                if (listenerWrapper.filterMatches(packet)) {
                    listenersToNotify.add(listenerWrapper.getListener());
                }
            }
        }

        for (final StanzaListener listener : listenersToNotify) {
            asyncGo(new Runnable() {
                @Override
                public void run() {
                    try {
                        listener.processPacket(packet);
                    } catch (Exception e) {
                        LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
                    }
                }
            });
        }

        // Loop through all collectors and notify the appropriate ones.
        for (PacketCollector collector: collectors) {
            collector.processPacket(packet);
        }

        // Notify the receive listeners interested in the packet
        listenersToNotify.clear();
        synchronized (syncRecvListeners) {
            for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
                if (listenerWrapper.filterMatches(packet)) {
                    listenersToNotify.add(listenerWrapper.getListener());
                }
            }
        }

        // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
        // threaded executor service and therefore keeps the order.
        singleThreadedExecutorService.execute(new Runnable() {
            @Override
            public void run() {
                for (StanzaListener listener : listenersToNotify) {
                    try {
                        listener.processPacket(packet);
                    } catch(NotConnectedException e) {
                        LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
                        break;
                    } catch (Exception e) {
                        LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
                    }
                }
            }
        });

AbstractXMPPConnection實(shí)現(xiàn)了XMPPConnection接口,各種Listener的注冊和回調(diào)就是在這個類里完成的,但如login,connect,shutdown等方法的具體實(shí)現(xiàn)是位于其子類中的。

連接過程

真正執(zhí)行連接動作的是XMPPTCPConnection中connectInternal的方法

protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
        closingStreamReceived.init();
        // Establishes the TCP connection to the server and does setup the reader and writer. Throws an exception if
        // there is an error establishing the connection
        connectUsingConfiguration();

        // We connected successfully to the servers TCP port
        initConnection();

        // Wait with SASL auth until the SASL mechanisms have been received
        saslFeatureReceived.checkIfSuccessOrWaitOrThrow();

        // Make note of the fact that we're now connected.
        connected = true;
        callConnectionConnectedListener();
    }

connectUsingConfiguration方法中,用配置類XMPPTCPConnectionConfiguration提供的hostAddress,timeout等數(shù)據(jù)創(chuàng)建一個Socket連接出來。隨后進(jìn)行了一些初始化,例如初始化reader,writer變量:

private void initReaderAndWriter() throws IOException {
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        if (compressionHandler != null) {
            is = compressionHandler.getInputStream(is);
            os = compressionHandler.getOutputStream(os);
        }
        // OutputStreamWriter is already buffered, no need to wrap it into a BufferedWriter
        writer = new OutputStreamWriter(os, "UTF-8");
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        // If debugging is enabled, we open a window and write out all network traffic.
        initDebugger();
    }

PacketWriter對包的發(fā)送進(jìn)行了封裝,該類里維護(hù)一個BlockingQueue,所有要發(fā)送的包都先插入到這個隊列中,同時起一個線程不停消費(fèi)這個隊列,最終是通過writer把數(shù)據(jù)寫往服務(wù)器

                        while (!queue.isEmpty()) {
                            Element packet = queue.remove();
                            writer.write(packet.toXML().toString());
                        }
                        writer.flush();

而PacketReader則是對包的讀取和解析進(jìn)行了封裝,類里面有個XmlPullParser,通過reader進(jìn)行了初始化

 packetReader.parser = PacketParserUtils.newXmppParser(reader);

然后起了一個線程不停進(jìn)行包的解析

            Async.go(new Runnable() {
                public void run() {
                    parsePackets();
                }
            }, "Smack Packet Reader (" + getConnectionCounter() + ")");
         }

解析出來的包回調(diào)到AbstractXMPPConnection類中的parseAndProcessStanza方法,最終調(diào)用各種已注冊好的StanzaListener、PacketCollector來處理

XMPPConnectionRegistry

這個靜態(tài)類中有個ConnectionCreationListener的集合

private final static Set<ConnectionCreationListener> connectionEstablishedListeners =
            new CopyOnWriteArraySet<ConnectionCreationListener>();

當(dāng)XMPPConnection初始化的時候,會通知給各個Listener

protected AbstractXMPPConnection(ConnectionConfiguration configuration) {
        saslAuthentication = new SASLAuthentication(this, configuration);
        config = configuration;
        // Notify listeners that a new connection has been established
        for (ConnectionCreationListener listener : XMPPConnectionRegistry.getConnectionCreationListeners()) {
            listener.connectionCreated(this);
        }
    }

像ReconnectionManager,PingManager等策略管理類,會在靜態(tài)代碼塊中直接注冊ConnectionCreationListener

static {
        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
            public void connectionCreated(XMPPConnection connection) {
                if (connection instanceof AbstractXMPPConnection) {
                    ReconnectionManager.getInstanceFor((AbstractXMPPConnection) connection);
                }
            }
        });
    }

ReconnectionManager

由于可以創(chuàng)建多個XMPPConnection的實(shí)例,ReconnectionManager的實(shí)例也有多個,和XMPPConnection一一對應(yīng),實(shí)際上ReconnectionManager持有了XMPPConnection的弱引用,用于進(jìn)行與Connection相關(guān)的操作。

類里面還定義了不同的重連策略ReconnectionPolicy,有按固定頻率重連的,也有按隨機(jī)間隔重連的,

private int timeDelay() {
                attempts++;

                // Delay variable to be assigned
                int delay;
                switch (reconnectionPolicy) {
                case FIXED_DELAY:
                    delay = fixedDelay;
                    break;
                case RANDOM_INCREASING_DELAY:
                    if (attempts > 13) {
                        delay = randomBase * 6 * 5; // between 2.5 and 7.5 minutes (~5 minutes)
                    }
                    else if (attempts > 7) {
                        delay = randomBase * 6; // between 30 and 90 seconds (~1 minutes)
                    }
                    else {
                        delay = randomBase; // 10 seconds
                    }
                    break;
                default:
                    throw new AssertionError("Unknown reconnection policy " + reconnectionPolicy);
                }

                return delay;
            }

ReconnectionManager向XMPPConnection注冊了ConnectionListener,當(dāng)XMPPConnection中發(fā)生連接異常時,如PacketWriter、PacketReader讀寫包異常時,會通過ConnectionListener中的connectionClosedOnError方法,通知ReconnectionManager進(jìn)行重連重試。

PingManager、ServerPingWithAlarmManager

PingManager實(shí)現(xiàn)了協(xié)議規(guī)定的定時發(fā)送Ping消息到服務(wù)器的策略,默認(rèn)是30分鐘的間隔。ServerPingWithAlarmManager是針對Android平臺的實(shí)現(xiàn),用AlarmManager來實(shí)現(xiàn)的定時策略,在代碼里寫死是30分鐘的頻率,這在移動端肯定是不適用的,另外也沒看到針對各種網(wǎng)絡(luò)環(huán)境的處理,看來為保證長連接的穩(wěn)定性,需要開發(fā)者自己再去實(shí)現(xiàn)一些心跳和重連策略

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 一、Smack庫概述 ????Smack是一個開源、易用的XMPP/Jabber客戶端庫,它使用Java語言開發(fā),...
    AndryYu閱讀 6,294評論 2 13
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時芥藍(lán)閱讀 42,373評論 11 349
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 換手機(jī)
    10e45c2d55b2閱讀 306評論 0 1