Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 透過 Socket 與伺服器通訊的完整實作(含 Demo)

編輯:關於 Android 程式設計

Socket 是 Android 上歷史悠久、也相當可靠的通訊方式。它不像 HTTP 那樣有著「一问一答」的限制,伺服器可以主動推送資料給客戶端,因此非常適合即時通訊、長連線通知等場景。代價是你要自己處理連線管理、訊息邊界、心跳偵測等細節。

以下整理一套可運行的骨架,大致分為五個部分。

整體架構

  1. SocketOutputThread:負責送訊息。訊息先進佇列,線程被喚醒後逐筆送出,並透過 Handler 回報成功或失敗。
  2. SocketInputThread:負責收訊息。這裡採用 NIO 的 Selector 而非阻塞式 read,是整份設計的關鍵——不必開一條線程定時輪詢去讀,沒資料時完全不吃 CPU。
  3. SocketHeartThread:週期性送心跳,偵測連線是否已斷。
  4. SocketThreadManager:統一管理上述三條線程的生命週期。
  5. TCPClient:以 NIO 封裝 SocketChannel 與 Selector,對外提供 sendMsg、reConnect、isConnect 等方法。

一、送訊息線程

public class SocketOutputThread extends Thread {

    private volatile boolean isStart = true;
    private static final String TAG = "socketOutputThread";

    // CopyOnWriteArrayList:讀取時不需要鎖,適合「少量寫入、頻繁遍歷」的佇列
    private final List<MsgEntity> sendMsgList = new CopyOnWriteArrayList<>();

    public void setStart(boolean isStart) {
        this.isStart = isStart;
        synchronized (this) { notify(); }
    }

    /** 把訊息放進佇列並喚醒送訊息線程 */
    public void addMsgToSendList(MsgEntity msg) {
        synchronized (this) {
            sendMsgList.add(msg);
            notify();
        }
    }

    private boolean sendMsg(byte[] msg) throws Exception {
        if (msg == null) {
            CLog.e(TAG, "sendMsg is null");
            return false;
        }
        TCPClient.instance().sendMsg(msg);
        return true;
    }

    @Override
    public void run() {
        while (isStart) {
            synchronized (sendMsgList) {
                for (MsgEntity msg : sendMsgList) {
                    Handler handler = msg.getHandler();
                    try {
                        sendMsg(msg.getBytes());
                        sendMsgList.remove(msg);
                        notifyResult(handler, msg.getBytes(), 1);   // 1 = 成功
                    } catch (Exception e) {
                        e.printStackTrace();
                        CLog.e(TAG, e.toString());
                        notifyResult(handler, msg.getBytes(), 0);   // 0 = 失敗
                    }
                }
            }
            synchronized (this) {
                try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }

    private void notifyResult(Handler handler, byte[] payload, int what) {
        if (handler != null) {
            Message message = new Message();
            message.obj = payload;
            message.what = what;
            handler.sendMessage(message);
        }
    }
}

這個設計的優點是:呼叫方只要把訊息丟進佇列並傳入一個 Handler,就能非同步地收到「送出去了」或「失敗了」的通知,完全不必關心底層何時真正寫入 socket。

二、收訊息線程(NIO)

public class SocketInputThread extends Thread {

    private volatile boolean isStart = true;
    private static final String TAG = "socket";

    public void setStart(boolean isStart) { this.isStart = isStart; }

    @Override
    public void run() {
        while (isStart) {
            if (NetManager.instance().isNetworkConnected()) {
                if (!TCPClient.instance().isConnect()) {
                    // 連線斷了就先睡一會兒,避免空轉
                    try {
                        sleep(Const.SOCKET_SLEEP_SECOND * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                readSocket();
            }
        }
    }

    public void readSocket() {
        Selector selector = TCPClient.instance().getSelector();
        if (selector == null) { return; }

        try {
            // 沒有資料時會阻塞在這裡,不佔用 CPU
            while (selector.select() > 0) {
                for (SelectionKey sk : selector.selectedKeys()) {
                    if (!sk.isReadable()) { continue; }

                    SocketChannel sc = (SocketChannel) sk.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    try {
                        sc.read(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    buffer.flip();

                    String received = "";
                    try {
                        received = Charset.forName("UTF-8")
                                .newDecoder().decode(buffer).toString();
                        CLog.e(TAG, received);

                        // 收到資料後用廣播丟給需要的地方
                        Intent i = new Intent(Const.BC);
                        i.putExtra("response", received);
                        MainActivity.s_context.sendBroadcast(i);
                    } catch (CharacterCodingException e) {
                        e.printStackTrace();
                    } finally {
                        buffer.clear();
                    }

                    try {
                        sk.interestOps(SelectionKey.OP_READ);
                        selector.selectedKeys().remove(sk);   // 必須手動移除
                    } catch (CancelledKeyException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException | ClosedSelectorException e) {
            e.printStackTrace();
        }
    }
}

selector.select() 是這裡的核心:它會在沒有資料可讀時讓線程進入等待,直到有事件才返回。相比「每隔 500 毫秒 read 一次」的輪詢寫法,這在待機模式下幾乎不消耗 CPU 與電量。另外別忘了每次處理完 SelectionKey 都要從 selectedKeys() 中移除,否則下次迴圈會重複處理同一筆。

三、心跳線程

class SocketHeartThread extends Thread {

    private volatile boolean isStop = false;
    private static SocketHeartThread s_instance;

    static synchronized SocketHeartThread instance() {
        if (s_instance == null) {
            s_instance = new SocketHeartThread();
        }
        return s_instance;
    }

    public void stopThread() { isStop = true; }

    @Override
    public void run() {
        isStop = false;
        while (!isStop) {
            // 發一個心跳看伺服器是否還在
            if (!TCPClient.instance().canConnectToServer()) {
                TCPClient.instance().reConnect();
            }
            try {
                Thread.sleep(Const.SOCKET_HEART_SECOND * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

四、線程管理

public class SocketThreadManager {

    private static SocketThreadManager s_manager;

    private SocketInputThread mInputThread;
    private SocketOutputThread mOutThread;
    private SocketHeartThread mHeartThread;

    public static SocketThreadManager sharedInstance() {
        if (s_manager == null) {
            s_manager = new SocketThreadManager();
            s_manager.startThreads();
        }
        return s_manager;
    }

    private SocketThreadManager() {
        mHeartThread = SocketHeartThread.instance();
        mInputThread = new SocketInputThread();
        mOutThread = new SocketOutputThread();
    }

    private void startThreads() {
        mHeartThread.start();
        mInputThread.setStart(true);
        mInputThread.start();
        mOutThread.setStart(true);
        mOutThread.start();
    }

    public void stopThreads() {
        mHeartThread.stopThread();
        mInputThread.setStart(false);
        mOutThread.setStart(false);
    }

    public static void releaseInstance() {
        if (s_manager != null) {
            s_manager.stopThreads();
            s_manager = null;
        }
    }

    /** 對外統一的送訊息入口 */
    public void sendMsg(byte[] buffer, Handler handler) {
        mOutThread.addMsgToSendList(new MsgEntity(buffer, handler));
    }
}

五、TCPClient(NIO 封裝)

public class TCPClient {

    private Selector selector;
    private SocketChannel socketChannel;

    private String hostIp;
    private int hostListenningPort;

    private static TCPClient s_tcp;
    public boolean isInitialized = false;

    public static synchronized TCPClient instance() {
        if (s_tcp == null) {
            s_tcp = new TCPClient(Const.SOCKET_SERVER, Const.SOCKET_PORT);
        }
        return s_tcp;
    }

    private TCPClient(String hostIp, int port) {
        this.hostIp = hostIp;
        this.hostListenningPort = port;
        try {
            initialize();
            isInitialized = true;
        } catch (Exception e) {
            isInitialized = false;
            e.printStackTrace();
        }
    }

    public void initialize() throws IOException {
        boolean done = false;
        try {
            socketChannel = SocketChannel.open(
                    new InetSocketAddress(hostIp, hostListenningPort));
            if (socketChannel != null) {
                socketChannel.socket().setTcpNoDelay(false);
                socketChannel.socket().setKeepAlive(true);
                socketChannel.socket().setSoTimeout(Const.SOCKET_READ_TIMOUT);
                socketChannel.configureBlocking(false);

                selector = Selector.open();
                if (selector != null) {
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    done = true;
                }
            }
        } finally {
            if (!done && selector != null) { selector.close(); }
            if (!done && socketChannel != null) { socketChannel.close(); }
        }
    }

    public void sendMsg(byte[] bytes) throws IOException {
        if (socketChannel == null) { throw new IOException(); }
        socketChannel.write(ByteBuffer.wrap(bytes));
    }

    public synchronized Selector getSelector() { return selector; }

    public boolean isConnect() {
        return isInitialized && socketChannel != null && socketChannel.isConnected();
    }

    public boolean reConnect() {
        closeTCPSocket();
        try {
            initialize();
            isInitialized = true;
        } catch (Exception e) {
            isInitialized = false;
            e.printStackTrace();
        }
        return isInitialized;
    }

    /** 以 urgent data 做輕量探活,比送完整心跳包便宜 */
    public boolean canConnectToServer() {
        try {
            if (socketChannel != null) {
                socketChannel.socket().sendUrgentData(0xff);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public void closeTCPSocket() {
        try { if (socketChannel != null) { socketChannel.close(); } } catch (IOException ignored) { }
        try { if (selector != null) { selector.close(); } } catch (IOException ignored) { }
    }
}

使用方式

// 傳入自訂 Handler,就能收到送出的成功/失敗回報
SocketThreadManager.sharedInstance().sendMsg(str.getBytes(), handler);

實作時必須注意的幾件事

訊息邊界問題。TCP 是串流協定,不代表一次 read 剛好對應一筆完整訊息。上面範例為求簡潔直接以 UTF-8 解碼,實務上必須自訂協定——常見做法是「4 位元組標頭記錄長度 + 訊息本文」,接收端先讀標頭再決定要收幾個位元組,並用緩衝區處理黏包與拆包的情況。這一點沒做好,長訊息或高頻訊息一定出錯。

線程與 Activity 生命週期。SocketThreadManager 是單例,必須在onCleared() 或 onDestroy() 中呼叫 releaseInstance(),否則 Activity 銷毀後線程仍在跑,會造成記憶體洩漏。

主執行緒禁止網路操作。Android 4.0 之後在新執行緒外執行 socket 連線會直接拋出 NetworkOnMainThreadException,因此 initialize() 一定要放在背景執行緒。

完整 Demo 下載:demo

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