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

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

編輯:中階開發

這一篇我們用一個實例,詳細說明 Android 環境下 NIO 非阻塞伺服器的開發方式。

先講結論:客戶端不建議使用 NIO。NIO 相對傳統 I/O 複雜得多,而它誕生的初衷是解決多執行緒的並發問題;在客戶端引入它,複雜度帶來的風險往往會抵銷掉效能收益。畢竟 NIO 是 Java 的,型別不易掌控。客戶端要用 C++、Java、C# 甚至 Flash ActionScript 都可以,選擇很多。

Echo Server 實作

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Server {
    public static void main(String[] args) {
        Selector selector = null;
        ServerSocketChannel ssc = null;
        try {
            selector = Selector.open();                       // 建立 Selector
            ssc = ServerSocketChannel.open();                 // 建立 ServerSocketChannel

            ssc.socket().bind(new InetSocketAddress(1987));   // 綁定 1987 埠
            ssc.configureBlocking(false);                     // 設為非阻塞
            ssc.register(selector, SelectionKey.OP_ACCEPT);   // 註冊關心的 accept 事件

            while (true) {
                int n = selector.select();                    // 取得就緒事件數量
                if (n < 1) continue;                          // 沒有事件就繼續輪詢

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    it.remove();                              // 記得移除,否則會重複處理

                    if (key.isAcceptable()) {                 // OP_ACCEPT
                        ServerSocketChannel ssc2 = (ServerSocketChannel) key.channel();
                        SocketChannel channel = ssc2.accept();
                        channel.configureBlocking(false);     // 同樣是非阻塞
                        channel.register(selector, SelectionKey.OP_READ);
                        System.out.println("Client: "
                                + channel.socket().getInetAddress().getHostName()
                                + ":" + channel.socket().getPort());
                    } else if (key.isReadable()) {            // OP_READ
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);   // 1KB 緩衝區
                        channel.read(buffer);
                        buffer.flip();                        // 準備讀出
                        channel.write(CharBuffer.wrap("it works".getBytes()));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                selector.close();
            } catch (IOException e) { }
        }
    }
}

這個框架其實問題不少

上面只是一個能跑的最小骨架,裡面藏的問題遠比看起來的多。如果你讀過 Mina 或 GlassFish 的原始碼,大概能一口氣指出十幾處——而且大多數都出在框架層面。這樣的伺服器一上真實流量,CPU 動不動就衝到 100%。

幾個比較明顯的:

· 每次 read 都重新 allocate 一個 1KB 的 ByteBuffer,高頻情境下會製造大量垃圾物件。

· 讀完立刻在同一個事件裡寫回,正是上一篇提到的讀寫未分離問題。

· 沒有處理客戶端斷線:read 回傳 -1 時應關閉通道並取消 key,否則該 key 會一直留在 Selector 裡空轉。

· 沒有處理 CancelledKeyException。

· it.remove() 這步絕對不能省,否則已處理過的 key 會在下一輪被重複取出。

下一篇會針對這些問題逐一修正,並給出更嚴謹的框架。

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