Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 中階開發

Android 開發進階之 NIO 非阻塞套件(八)

編輯:中階開發

整個 DDMS 裡最能體現 Android NIO 框架的,莫過於 MonitorThread.java 這支檔案。PC 與 Android 手機之間的同步機制,以及 NIO 非阻塞編程的精隨,幾乎都濃縮在這裡。

final class MonitorThread extends Thread {
    private static final int CLIENT_READY = 2;
    private static final int CLIENT_DISCONNECTED = 3;

    private volatile boolean mQuit = false;
    private ArrayList<Client> mClientList;                 // 用陣列保存客戶端資訊
    private Selector mSelector;
    private HashMap<Integer, ChunkHandler> mHandlerMap;
    private ServerSocketChannel mDebugSelectedChan;        // 一個用於除錯的伺服器通道
    private int mNewDebugSelectedPort;
    private int mDebugSelectedPort = -1;
    private Client mSelectedClient = null;
    private static MonitorThread mInstance;

    private MonitorThread() {
        super("Monitor");
        mClientList = new ArrayList<Client>();
        mHandlerMap = new HashMap<Integer, ChunkHandler>();
        mNewDebugSelectedPort = DdmPreferences.getSelectedDebugPort();
    }

    static MonitorThread createInstance() {                // 建立實例
        return mInstance = new MonitorThread();
    }

    static MonitorThread getInstance() {                   // 取得實例
        return mInstance;
    }

    synchronized void setDebugSelectedPort(int port) throws IllegalStateException {
        if (mInstance == null) return;
        if (androidDebugBridge.getClientSupport() == false) return;

        if (mDebugSelectedChan != null) {
            Log.d("ddms", "Changing debug-selected port to " + port);
            mNewDebugSelectedPort = port;
            wakeup();                                      // 喚醒所有 Selector
        } else {
            // 改設定 mNewDebugSelectedPort 而非 mDebugSelectedPort,
            // 讓它能在下一輪自動生效
            mNewDebugSelectedPort = port;
        }
    }

    synchronized void setSelectedClient(Client selectedClient) {
        if (mInstance == null) return;
        if (mSelectedClient != selectedClient) {
            Client oldClient = mSelectedClient;
            mSelectedClient = selectedClient;
            if (oldClient != null)    oldClient.update(Client.CHANGE_PORT);
            if (mSelectedClient != null) mSelectedClient.update(Client.CHANGE_PORT);
        }
    }

    Client getSelectedClient() { return mSelectedClient; }

    boolean getRetryOnBadHandshake() { return true; }

    Client[] getClients() {
        synchronized (mClientList) {
            return mClientList.toArray(new Client[0]);
        }
    }

    synchronized void registerChunkHandler(int type, ChunkHandler handler) {
        if (mInstance == null) return;
        synchronized (mHandlerMap) {
            if (mHandlerMap.get(type) == null) {
                mHandlerMap.put(type, handler);
            }
        }
    }

主線程:Selector 的事件迴圈

    @Override
    public void run() {                                    // 本類別的主要線程
        Log.d("ddms", "Monitor is up");
        try {
            mSelector = Selector.open();
        } catch (IOException ioe) {
            Log.logAndDisplay(LogLevel.ERROR, "ddms",
                "Failed to initialize Monitor Thread: " + ioe.getMessage());
            return;
        }

        while (!mQuit) {
            try {
                synchronized (mClientList) { }

                try {
                    if (androidDebugBridge.getClientSupport()) {
                        if ((mDebugSelectedChan == null ||
                             mNewDebugSelectedPort != mDebugSelectedPort) &&
                            mNewDebugSelectedPort != -1) {
                            if (reopenDebugSelectedPort()) {
                                mDebugSelectedPort = mNewDebugSelectedPort;
                            }
                        }
                    }
                } catch (IOException ioe) {
                    Log.e("ddms", "Failed to reopen debug port for Selected Client to: "
                            + mNewDebugSelectedPort);
                    Log.e("ddms", ioe);
                    mNewDebugSelectedPort = mDebugSelectedPort;   // no retry
                }

                int count;
                try {
                    count = mSelector.select();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    continue;
                } catch (CancelledKeyException cke) {
                    continue;
                }

                if (count == 0) continue;
                // 這裡的寫法並不理想:因為這段 NIO 是跑在 PC 端的 DDMS,
                // 問題不明顯,但把輪詢塞進同一個 while 裡效率不高,CPU 佔用容易飆高。

                Set<SelectionKey> keys = mSelector.selectedKeys();
                Iterator<SelectionKey> iter = keys.iterator();   // 用迭代器取得選擇鍵

                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();

                    try {
                        if (key.attachment() instanceof Client) {
                            processClientActivity(key);
                        } else if (key.attachment() instanceof Debugger) {
                            processDebuggerActivity(key);
                        } else if (key.attachment() instanceof MonitorThread) {
                            processDebugSelectedActivity(key);
                        } else {
                            Log.e("ddms", "unknown activity key");
                        }
                    } catch (Exception e) {
                        Log.e("ddms", "Exception during activity from Selector.");
                        Log.e("ddms", e);
                    }
                }
            } catch (Exception e) {
                Log.e("ddms", "Exception MonitorThread.run()");
                Log.e("ddms", e);
            }
        }
    }

這裡有個細節值得記住:多執行緒環境下,ConcurrentHashMap 通常比 HashMap 更安全也更有效率,是相當值得推薦的替代品。

處理客戶端資料

    private void processClientActivity(SelectionKey key) {
        Client client = (Client) key.attachment();
        try {
            if (key.isReadable() == false || key.isValid() == false) {
                Log.d("ddms", "Invalid key from " + client + ". Dropping client.");
                dropClient(client, true /* notify */);
                return;
            }

            client.read();
            JdwpPacket packet = client.getJdwpPacket();
            while (packet != null) {
                if (packet.isDdmPacket()) {
                    // 非主動回覆的 DDM 請求,直接交給 handler
                    assert !packet.isReply();
                    callHandler(client, packet, null);
                    packet.consume();
                } else if (packet.isReply()
                        && client.isResponseToUs(packet.getId()) != null) {
                    // 對先前 DDM 請求的回覆
                    ChunkHandler handler = client.isResponseToUs(packet.getId());
                    if (packet.isError()) {
                        client.packetFailed(packet);
                    } else if (packet.isEmpty()) {
                        Log.d("ddms", "Got empty reply for 0x"
                                + Integer.toHexString(packet.getId()) + " from " + client);
                    } else {
                        callHandler(client, packet, handler);
                    }
                    packet.consume();
                    client.removeRequestId(packet.getId());
                } else {
                    // 轉發給 debugger
                    client.forwardPacketToDebugger(packet);
                }
                packet = client.getJdwpPacket();
            }
        } catch (CancelledKeyException e) {        // 這個異常一定要正確處理
            dropClient(client, true /* notify */);
        } catch (IOException ex) {
            dropClient(client, true /* notify */);
        } catch (Exception ex) {
            Log.e("ddms", ex);
            dropClient(client, true /* notify */);

            if (ex instanceof BufferOverflowException) {   // 可能是緩衝區溢出
                Log.w("ddms", "Client data packet exceeded maximum buffer size " + client);
            } else {
                Log.e("ddms", ex);
            }
        }
    }

    private void callHandler(Client client, JdwpPacket packet, ChunkHandler handler) {
        // 收到第一個 DDM 封包時,廣播「就緒」訊息
        if (!client.ddmSeen()) broadcast(CLIENT_READY, client);

        ByteBuffer buf = packet.getPayload();
        int type = buf.getInt();
        int length = buf.getInt();
        boolean reply = true;

        if (handler == null) {
            // 不是回覆,找出誰需要它
            synchronized (mHandlerMap) {
                handler = mHandlerMap.get(type);
                reply = false;
            }
        }

        if (handler == null) {
            Log.w("ddms", "Received unsupported chunk type "
                    + ChunkHandler.name(type) + " (len=" + length + ")");
        } else {
            ByteBuffer ibuf = buf.slice();
            ByteBuffer roBuf = ibuf.asReadOnlyBuffer();     // 強制唯讀
            roBuf.order(ChunkHandler.CHUNK_ORDER);
            synchronized (mClientList) {
                handler.handleChunk(client, type, roBuf, reply, packet.getId());
            }
        }
    }

    synchronized void dropClient(Client client, boolean notify) {
        if (mInstance == null) return;
        synchronized (mClientList) {
            if (mClientList.remove(client) == false) return;
        }
        client.close(notify);
        broadcast(CLIENT_DISCONNECTED, client);
        wakeup();
    }

處理 debugger 連線

    private void processDebuggerActivity(SelectionKey key) {
        Debugger dbg = (Debugger) key.attachment();
        try {
            if (key.isAcceptable()) {                 // 處理 Server 回應這個事件
                try {
                    acceptNewDebugger(dbg, null);
                } catch (IOException ioe) {
                    Log.w("ddms", "debugger accept() failed");
                }
            } else if (key.isReadable()) {            // 收到資料,可以讀取
                processDebuggerData(key);
            } else {
                Log.d("ddm-debugger", "key in unknown state");
            }
        } catch (CancelledKeyException cke) {
            // key 已被取消,可以忽略。NIO 的這個異常很多入門開發者容易忘記處理。
        }
    }

    private void acceptNewDebugger(Debugger dbg, ServerSocketChannel acceptChan)
            throws IOException {                      // 這裡用到了阻塞方式
        synchronized (mClientList) {
            SocketChannel chan;
            if (acceptChan == null) chan = dbg.accept();
            else                    chan = dbg.accept(acceptChan);

            if (chan != null) {
                chan.socket().setTcpNoDelay(true);
                wakeup();
                try {
                    chan.register(mSelector, SelectionKey.OP_READ, dbg);
                } catch (IOException ioe) {
                    dbg.closeData();
                    throw ioe;
                } catch (RuntimeException re) {
                    dbg.closeData();
                    throw re;
                }
            } else {
                Log.w("ddms", "ignoring duplicate debugger");
            }
        }
    }

    private void processDebuggerData(SelectionKey key) {
        Debugger dbg = (Debugger) key.attachment();
        try {
            dbg.read();
            JdwpPacket packet = dbg.getJdwpPacket();
            while (packet != null) {
                dbg.forwardPacketToClient(packet);
                packet = dbg.getJdwpPacket();
            }
        } catch (IOException ioe) {
            Log.d("ddms", "Closing connection to debugger " + dbg);
            dbg.closeData();
            Client client = dbg.getClient();
            if (client != null) {
                // 一併回收客戶端連線,交由 DeviceMonitor 重開
                client.getDeviceImpl().getMonitor()
                      .addClientToDropAndReopen(client, IDebugPortProvider.NO_STATIC_PORT);
            }
        }
    }

    private void wakeup() { mSelector.wakeup(); }

    synchronized void quit() {
        mQuit = true;
        wakeup();
        try {
            this.join();
            synchronized (mClientList) {
                for (Client c : mClientList) {
                    c.close(false /* notify */);
                    broadcast(CLIENT_DISCONNECTED, c);
                }
                mClientList.clear();
            }
            if (mDebugSelectedChan != null) {
                mDebugSelectedChan.close();
                mDebugSelectedChan.socket().close();
                mDebugSelectedChan = null;
            }
            mSelector.close();
        } catch (InterruptedException IE) {
            IE.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mInstance = null;
    }

    synchronized void addClient(Client client) {
        if (mInstance == null) return;
        synchronized (mClientList) {
            mClientList.add(client);
            try {
                wakeup();
                client.register(mSelector);
                Debugger dbg = client.getDebugger();
                if (dbg != null) dbg.registerListener(mSelector);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    private void broadcast(int event, Client client) {
        HashSet<ChunkHandler> set;
        synchronized (mHandlerMap) {
            set = new HashSet<ChunkHandler>(mHandlerMap.values());
        }
        Iterator<ChunkHandler> iter = set.iterator();
        while (iter.hasNext()) {
            ChunkHandler handler = iter.next();
            switch (event) {
                case CLIENT_READY:
                    try {
                        handler.clientReady(client);
                    } catch (IOException ioe) {
                        // 這個 client 出問題了,下次再操作它時就會被剔掉,
                        // 這裡先吞下異常,假設稍後會善後。
                        Log.w("ddms", "Got exception while broadcasting 'ready'");
                        return;
                    }
                    break;
                case CLIENT_DISCONNECTED:
                    handler.clientDisconnected(client);
                    break;
                default:
                    throw new UnsupportedOperationException();
            }
        }
    }

「debug selected」埠的開啟與處理

    private boolean reopenDebugSelectedPort() throws IOException {
        Log.d("ddms", "reopen debug-selected port: " + mNewDebugSelectedPort);
        if (mDebugSelectedChan != null) mDebugSelectedChan.close();

        mDebugSelectedChan = ServerSocketChannel.open();
        mDebugSelectedChan.configureBlocking(false);       // Selector 的必要條件

        InetSocketAddress addr = new InetSocketAddress(
                InetAddress.getByName("localhost"), mNewDebugSelectedPort);
        mDebugSelectedChan.socket().setReuseAddress(true); // 啟用 SO_REUSEADDR

        try {
            mDebugSelectedChan.socket().bind(addr);
            if (mSelectedClient != null) {
                mSelectedClient.update(Client.CHANGE_PORT);
            }
            mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this);
            return true;
        } catch (java.net.BindException e) {
            displayDebugSelectedBindError(mNewDebugSelectedPort);
            mDebugSelectedChan = null;                     // 不再嘗試重開
            mNewDebugSelectedPort = -1;
            return false;
        }
    }

    private void processDebugSelectedActivity(SelectionKey key) {
        assert key.isAcceptable();
        ServerSocketChannel acceptChan = (ServerSocketChannel) key.channel();

        if (mSelectedClient != null) {
            Debugger dbg = mSelectedClient.getDebugger();
            if (dbg != null) {
                try {
                    acceptNewDebugger(dbg, acceptChan);
                } catch (IOException ioe) {
                    // client 應該已經消失,繼續跑
                }
                return;
            }
        }

        Log.w("ddms", "Connection on 'debug selected' port, but none selected");
        try {
            SocketChannel chan = acceptChan.accept();
            chan.close();
        } catch (IOException ioe) {
            // 非預期情況,client 應該已消失,繼續跑
        } catch (NotYetBoundException e) {
            displayDebugSelectedBindError(mDebugSelectedPort);
        }
    }

    private void displayDebugSelectedBindError(int port) {
        String message = String.format(
            "Could not open Selected VM debug port (%1$d). Make sure you do not have "
          + "another instance of DDMS or of the eclipse plugin running. If it's being "
          + "used by something else, choose a new port number in the preferences.", port);
        Log.logAndDisplay(LogLevel.ERROR, "ddms", message);
    }
}

讀完這份程式碼之後

從上面的實作可以看出一件事:Android 開原始碼中屬於 PC 端的部分品質並不算理想,不少地方是靠反覆打補丁硬撐起來的,某些習慣也談不上到位。

這個 NIO 範例牽涉的物件相當多——Client、Debugger、ChunkHandler、DeviceMonitor 彼此環環相扣,光看單一檔案很難拼出全貌。建議的作法是先畫出 UML 類別圖與時序圖,把「誰註冊了什麼事件、事件回來之後交給誰」這條線拉直,再回頭讀每個物件的細節,理解起來會清晰很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved