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

Android Socket 通訊實作:用常駐 Service 打造長連線客戶端

編輯:關於 Android 程式設計

Android 與伺服器通訊主要有兩條路:HTTP 與 Socket。兩者最大的差異在連線模型。

HTTP 走的是「請求—回應」:客戶端發請求才建立通道,伺服器回應後連線即可關閉。伺服器無法主動推資料給客戶端,想要即時性就得靠輪詢,延遲與耗電都不理想。

Socket 則是在雙方建立連線後維持通道,隨時雙向傳輸。伺服器可以主動推送訊息,不必等客戶端發問。它也被稱為套接字,本質上是一層抽象,在程式內部提供對外通訊的埠資訊。特性是資料遺失率低、使用簡單、易於移植。

連線模型的基礎

本案例基於 TCP 協議。

服務端:先建立 ServerSocket 並指定埠號,呼叫 accept() 等待連線。accept() 是阻塞的,直到有客戶端連上才回傳 Socket 物件,之後透過 InputStream 讀取資料。

ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();          // 阻塞等待
InputStream in = socket.getInputStream();

客戶端:建立 Socket 並指定伺服器 IP 與埠號,取得 OutputStream 寫入資料即可。

Socket socket = new Socket("172.168.10.108", 8080);
OutputStream out = socket.getOutputStream();
out.write(data);

但在 Android 上還有兩個現實問題:一是主線程不能做網路 I/O,二是 App 被切到背景後連線不該跟著斷。因此實務上會把 Socket 邏輯放進常駐 Service,並拆成幾個各司其職的執行緒。

整體架構

本實作分層如下:

  • IMService:常駐 Service,負責通知、心跳排程、網路狀態檢查,並把收到的訊息以廣播丟給 UI。
  • Communication:單例,作為門面(Facade),對外暴露「加入待送佇列」「喚醒發送」等簡潔 API。
  • MessageWorker:发送執行緒,從送出路徑佇列取資料交給網路層;同時負責定時心跳。
  • NetTransportWorker:網路執行緒,處理連線建立、讀取、寫入、斷線重連。
  • ProtocolConst:集中管理伺服器位址與埠號。
  • BootReceiver:開機自啟,確保 Service 隨裝置啟動。

專案結構:

IMService:常駐與通知

public class IMService extends Service {

    static Communication communication;
    public static String messageTag = "com.gys.im.CYEJIMActivity";
    public static Notification notification;
    public static int messageId = 10000;

    private NotificationManager mNM;
    boolean isconnected;
    Timer timer = new Timer();

    @Override
    public void onCreate() {
        communication = Communication.newInstance();
        communication.setReceiver(this);

        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
        notification.number = 1;

        // 週期性檢查網路狀態
        timer.schedule(timerTask, 1000, 2000);
    }

    /** 網路層收到的訊息,轉成廣播丟給 UI */
    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            String message = msg.obj.toString();
            if (message.equals("start\n")) {
                start_check_in();       // 伺服器確認連線,啟動心跳
            } else {
                Intent intent = new Intent(messageTag);
                intent.putExtra("message", message);
                IMService.this.sendBroadcast(intent);
            }
        }
    };

    public TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            isconnected = checkNetwork();
            if (!isconnected) {
                showNotification("", "");
            }
        }
    };

    /** 外部呼叫 this 把訊息塞進發送佇列 */
    public static void addPacket(String str) {
        communication.addPacket(str);
    }

    public static void wakeUp() {
        communication.wakeUp();
    }

    protected void start_check_in() {
        communication.start_check_in();
    }

    public boolean checkNetwork() {
        ConnectivityManager cwjManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cwjManager.getActiveNetworkInfo() != null
            && cwjManager.getActiveNetworkInfo().isAvailable();
    }

    private void showNotification(String statusInfo, String messageContent) {
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);
        notification.when = System.currentTimeMillis();
        notification.tickerText = statusInfo;
        notification.setLatestEventInfo(this, "test", messageContent, contentIntent);
        notification.vibrate = new long[]{100, 250, 100, 500};
        mNM.notify(messageId, notification);
        notification.number++;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNM.cancel(messageId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;    // 不需要綁定,純常駐
    }
}

這裡有兩點值得注意:一是收到 "start\n" 並不是業務資料,而是伺服器對心跳的確認回覆,因此要另外分流;二是 Notification 那套 API 已在新版被大量替換,新專案請改用 NotificationCompat.Builder 搭配 Channel。

Communication:門面與單例

把兩個 Worker 的啟動與組合收在這裡,對外只暴露少數方法,呼叫方不必知道裡面有幾條執行緒:

public class Communication {

    private NetTransportWorker transportWorker;
    private MessageWorker messageWorker;
    private static Communication instance;

    private Communication() {
        transportWorker = new NetTransportWorker();
        transportWorker.start();
        messageWorker = new MessageWorker(transportWorker);
        messageWorker.start();
    }

    public static Communication newInstance() {
        if (instance == null) instance = new Communication();
        return instance;
    }

    public void setReceiver(IMService service) {
        transportWorker.setRecever(service);
    }

    /** 把訊息放進待送佇列 */
    public void addPacket(String packet) {
        messageWorker.addPacket(packet);
    }

    public void wakeUp() {
        messageWorker.wakeUp();
    }

    public void start_check_in() {
        messageWorker.start_check_in();
    }

    /** 取得所有尚未讀取的回覆,供非活動畫面稍後補讀 */
    public Queue<String> getReceivePackets() {
        return transportWorker.receiveQueue;
    }

    public String newSessionID() {
        return String.valueOf(System.currentTimeMillis());
    }
}

MessageWorker:发送佇列與心跳

這條執行緒的核心是一個 while(true) 迴圈搭配 wait/notify:待送佇列有東西就寫出去,沒東西就掛起等待被喚醒。心跳則用 Timer 週期性往佇列裡丟一個封包。

public class MessageWorker extends Thread {

    protected NetTransportWorker worker;
    protected Queue<String> sendQueue;
    protected Timer timer;
    protected TimerTask task;

    // 週期性發送在線確認封包
    protected final long delay = 30000;

    protected MessageWorker(final NetTransportWorker worker) {
        this.worker = worker;
        sendQueue = new ConcurrentLinkedQueue<String>();

        task = new TimerTask() {
            @Override
            public void run() {
                addPacket("hello\n");
                wakeUp();
            }
        };
    }

    /** 取得本機 IP,除錯時很有用 */
    public static String getLocalHostIp() {
        String ipaddress = "no_data";
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                Enumeration<InetAddress> inet = en.nextElement().getInetAddresses();
                while (inet.hasMoreElements()) {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip.getHostAddress())) {
                        return ipaddress = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            System.out.print("獲取IP 失敗" + e.toString());
        }
        return ipaddress;
    }

    protected void start_check_in() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(task, delay, delay);
        }
    }

    public void addPacket(String packet) {
        sendQueue.add(packet);
        wakeUp();
    }

    public synchronized void wakeUp() {
        notify();
    }

    @Override
    public synchronized void run() {
        while (true) {
            try {
                while (sendQueue.size() > 0) {
                    String packet = sendQueue.peek();
                    if (worker.writeBuf(packet.getBytes("UTF8"))) {
                        sendQueue.poll();
                    } else {
                        sendQueue.clear();      // 寫失敗就整批丟棄,避免積壓
                    }
                }
                wait();     // 佇列空了就掛起
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

用 ConcurrentLinkedQueue 而非一般 Queue,是因為多執行緒會同時讀寫這個佇列,非同步容器在這種情況下會出問題。

NetTransportWorker:連線、讀寫與重連

這是最核心的一條執行緒,用一個狀態機在「建立連線」與「資料傳輸」之間切換:

public class NetTransportWorker extends Thread {

    protected Socket socket = null;
    protected static final int CONNECT_TIMEOUT = 10000;
    protected static final int READ_TIMEOUT    = 60000;
    protected static final int RECONNECT_TIME  = 30000;

    protected final byte connect = 1;
    protected byte state = connect;
    protected boolean onWork = true;

    public static final String sysError = "與服務器連接斷開了,馬上重新連接!";

    protected IMService service;
    protected Queue<String> receiveQueue;
    DataOutputStream output;
    DataInputStream input;

    protected NetTransportWorker() {
        onWork = true;
        receiveQueue = new ConcurrentLinkedQueue<String>();
    }

    protected void setRecever(IMService service) {
        this.service = service;
    }

    @Override
    public void run() {
        while (onWork) {
            switch (state) {
                case connect: connect(); break;
                case running: running(); break;
            }
        }
    }

    /** 資料讀取迴圈 */
    private synchronized void running() {
        try {
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int number;
            while ((number = input.read(buffer, 0, buffer.length)) > 0) {
                baos.write(buffer, 0, number);
                String info = new String(baos.toByteArray());

                Message mess = new Message();
                mess.obj = info;
                service.handler.sendMessage(mess);
                baos.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendInfoMessageToUI(sysError);
            close();
        }
    }

    /** 寫入前先確認連線狀態,避免對已關閉的 socket 操作 */
    protected final boolean writeBuf(byte[] data) throws IOException {
        if (socket != null && socket.isConnected()
                && output != null
                && !socket.isOutputShutdown()
                && state == running) {
            output.write(data);
            output.flush();
            return true;
        }
        return false;
    }

    private void sendInfoMessageToUI(String text) {
        // 可在此把錯誤訊息回拋給 UI 層
    }

    protected synchronized void reconnect() {
        close();
    }

    private synchronized void connect() {
        try {
            SocketAddress sa = new InetSocketAddress(ProtocolConst.ip, ProtocolConst.port);
            socket = new Socket();
            socket.setSoTimeout(READ_TIMEOUT);
            socket.setTcpNoDelay(true);
            socket.connect(sa, CONNECT_TIMEOUT);

            output = new DataOutputStream(socket.getOutputStream());
            input  = new DataInputStream(socket.getInputStream());

            if (socket.isConnected()) {
                state = running;
                // 送出一個驗證封包,伺服器回覆 start 代表心跳已啟動
                writeBuf("start\n".getBytes("UTF8"));
            } else {
                sendInfoMessageToUI("服務器連接失敗" + (RECONNECT_TIME / 1000) + "秒後再嘗試連接");
                wait(RECONNECT_TIME);
                reconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendInfoMessageToUI((RECONNECT_TIME / 1000) + "秒後再嘗試連接");
            try {
                wait(RECONNECT_TIME);
                reconnect();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

    private void close() {
        state = connect;
        try {
            if (socket != null) socket.close();
            if (input != null) input.close();
            if (output != null) output.close();
            socket = null; input = null; output = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

幾個設計意圖:

  • setTcpNoDelay(true) 關閉 Nagle 演算法,即時通訊場景下能明顯降低小包延遲。
  • setSoTimeout(READ_TIMEOUT) 讓 read 不會永遠阻塞,逾時拋異常後可走重連流程。
  • 斷線後不是立刻重連,而是等待 RECONNECT_TIME,避免伺服器掛掉時客戶端瘋狂重試造成雪崩。

ProtocolConst 與 BootReceiver

把位址集中在一個類別,方便日後切換環境:

public class ProtocolConst {
    protected static final String ip = "192.168.1.167";
    protected static final int port = 4321;
}

開機時自動拉起 Service:

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        context.startService(new Intent(context, IMService.class));
    }
}

MainActivity:UI 與 Service 的橋樑

Activity 透過 IMService.addPacket() 發送訊息,並用動態註冊的 BroadcastReceiver 接收回覆:

public class MainActivity extends Activity implements OnClickListener {

    EditText sendContent;
    EditText showContent;
    ReceiverHandler rh;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sendContent = findViewById(R.id.sendcontent);
        showContent = findViewById(R.id.showcontent);

        findViewById(R.id.send).setOnClickListener(this);
        findViewById(R.id.send_code).setOnClickListener(this);
        findViewById(R.id.send_close_code).setOnClickListener(this);

        // 啟動常駐 Service
        startService(new Intent(this, IMService.class));
    }

    /** 動態註冊的廣播接收器 */
    public class ReceiverHandler extends BroadcastReceiver {
        public void registerAction(String action) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);
            registerReceiver(this, filter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (IMService.messageTag.equals(intent.getAction())) {
                Message mess = new Message();
                mess.obj = intent.getStringExtra("message");
                handler.sendMessage(mess);
            }
        }
    }

    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            showContent.append(msg.obj.toString());
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        rh = new ReceiverHandler();
        rh.registerAction(IMService.messageTag);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(rh);      // 務必反註冊,否則記憶體洩漏
    }

    /** 封包格式:以 JSON 承載指令,並以 \n 作為封包分隔符 */
    public static String createPar(String productId) {
        JSONObject menu = new JSONObject();
        try {
            menu.put("flag", "0");
            menu.put("msg", "播放商品視頻");
            menu.put("productId", productId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return menu.toString();
    }

    @Override
    public void onClick(View v) {
        String text = sendContent.getText().toString();
        if (text == null || text.equals("")) return;

        switch (v.getId()) {
            case R.id.send:
                text = createPar(text) + "\n";
                break;
        }
        IMService.addPacket(text);
        IMService.wakeUp();
        sendContent.setText("");
    }
}

這裡有個實務上很重要的約定:每個封包以 \n 結尾。TCP 是串流協議,沒有「訊息邊界」的概念,一次 read 可能讀到半個封包,也可能讀到一個半。用分隔符切分是最簡單的解法,正式專案則建議在封包前加上長度欄位(length-prefixed),並用緩衝區累積未完成的資料。

版面與權限

版面很樸素:輸入框、顯示區,加上發送、連線、中斷等按鈕:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/sendcontent"
        android:layout_width="245dp"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/showcontent"
        android:layout_width="268dp"
        android:layout_height="fill_parent"
        android:inputType="textMultiLine" />

    <Button android:id="@+id/send" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="發送" />
    <Button android:id="@+id/send_code" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="彈出二維碼" />
    <Button android:id="@+id/send_close_code" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="關閉二維碼" />

</LinearLayout>

清單檔需要網路與開機啟動相關權限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service android:name="com.gys.service.IMService" />

<receiver android:name="com.gys.BroadCast.BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

注意 BootReceiver 的 intent-filter 應該是 BOOT_COMPLETED,而不是 category HOME,否則接收器不會在開機時被觸發。

小結

整份實作可以濃縮成一句話:Service 負責生命週期,兩條執行緒分別負責送與收,佇列負責解耦,狀態機負責重連。

若要往正式環境推進,還有幾件事值得補上:加入心跳逾時主動斷線的機制(目前只有發送沒有逾時偵測)、改用 length-prefixed 封包格式、把 Notification 與 Handler 相關 API 更新到目前版本,以及在 Android 8.0 以上改用 startForegroundService() 搭配前台通知,否則常駐 Service 會被系統限制。下一篇再來談服務端的實作與兩端對接。

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