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

Java Socket 通信實戰(三):JSON 數據交互與多客戶端並發改造

編輯:關於 Android 程式設計

前言:連續幾天摸 socket,手感愈來愈順,但還是得多寫才會熟。業精於勤荒於嬉,行成於思毀於隨。這次我寫了一個比較貼近真實專案的練習:模擬兩個「接口」,客戶端把 JSON 拋給伺服器,伺服器處理完再把結果回傳。寫完單客戶端版本後,我又動手把它改造成能同時應對多個客戶端的樣子。

一、伺服器端:單客戶端版本

import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class JsonServer {
    public static void main(String args[]) {
        ServerSocket ss = null;
        Socket s = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        try {
            ss = new ServerSocket(3320);
            s = ss.accept();
            System.out.println("Client :" + s.getInetAddress() + " : " + s.getPort()
                               + " 已連接》》》》》》");
            dos = new DataOutputStream(s.getOutputStream());
            dis = new DataInputStream(s.getInputStream());
            while (true) {
                String data = dis.readUTF();
                System.out.println(data);
                if (null != data) {
                    if (!data.contains("data")) {
                        // 接口一:兩個加數,回傳和
                        JSONObject jo = new JSONObject(data);
                        int a = jo.getInt("numA");
                        int b = jo.getInt("numB");
                        dos.writeUTF(creatSumJson(a, b));
                    } else {
                        // 接口二:自增運算,每加一次就推送一次結果
                        JSONObject jo = new JSONObject(data);
                        int a = jo.getInt("data");
                        for (int i = 0; i < 100; i++) {
                            a++;
                            dos.writeUTF(createRandomJson(a));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                dis.close(); dos.close(); s.close(); ss.close();
                System.out.print("鏈接已斷開");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /** 模擬專案中的接口:自增後封裝成 JSON */
    public static String createRandomJson(int a) {
        JSONObject s = new JSONObject();
        try {
            s.put("data", a);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    /** 模擬專案中的接口:兩數相加後回傳 */
    public static String creatSumJson(int a, int b) {
        JSONObject s = new JSONObject();
        try {
            s.put("sum", a + b);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }
}

二、客戶端

package mysocket.jsonway;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;

public class JsonClient {
    public static void main(String args[]) {
        DataOutputStream dos = null;
        Thread chat = null;
        Socket socket = null;
        DataInputStream dis = null;
        try {
            socket = new Socket("127.0.0.1", 3320);
            dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(createRandomJson());   // 先送一個隨機數,觸發伺服器連續推送

            chat = new Thread(new ChatThread(socket));   // 獨立執行緒負責收
            chat.start();
            socket.setKeepAlive(true);

            int i = 0;
            while (i <= 100) {
                Thread.sleep(1000);
                dos.writeUTF(creatSumJson());   // 每兩秒送一組加數
                i++;
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                dos.close(); socket.close(); chat.stop();
                System.out.print("鏈接已斷開");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /** 接口二參數:20 以內隨機數 */
    public static String createRandomJson() {
        JSONObject s = new JSONObject();
        try {
            s.put("data", new Random().nextInt(20));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    /** 接口一參數:兩個 100 以內隨機數 */
    public static String creatSumJson() {
        JSONObject s = new JSONObject();
        try {
            s.put("numA", new Random().nextInt(100));
            s.put("numB", new Random().nextInt(100));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }
}
package mysocket.jsonway;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/** 專門負責讀取伺服器推送的訊息 */
public class ChatThread implements Runnable {
    private Socket s = null;
    DataInputStream dis = null;

    public ChatThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            dis = new DataInputStream(s.getInputStream());
            while (true) {
                System.out.println(dis.readUTF());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

先啟動伺服器,再啟動客戶端,執行結果如下:

三、升級:支援多個客戶端

寫到這裡我意識到一個明顯的缺陷:目前只能一對一連線,而真實專案裡往往是大量客戶端同時連上一台伺服器。所以伺服器必須改造。

核心思路很簡單——用一個迴圈持續 accept(),每接一個連線就丟給一個新執行緒去處理:

public static void main(String args[]) {
    ServerSocket ss = null;
    Socket s = null;
    Thread thread = null;
    try {
        ss = new ServerSocket(3320);
        while (true) {
            s = ss.accept();
            System.out.println("Client :" + s.getInetAddress() + " : " + s.getPort()
                               + " 已連接》》》》》》");
            thread = new Thread(new ServerThread(s));
            thread.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

主線程只負責接客,實際的資料處理全部搬到 ServerThread 裡:

package mysocket.versionone;

import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket s = null;
    DataInputStream dis = null;
    DataOutputStream dos = null;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            while (true) {
                dos = new DataOutputStream(s.getOutputStream());
                dis = new DataInputStream(s.getInputStream());
                String data = dis.readUTF();
                System.out.println(data);
                if (null != data) {
                    if (!data.contains("data")) {
                        JSONObject jo = new JSONObject(data);
                        int a = jo.getInt("numA");
                        int b = jo.getInt("numB");
                        dos.writeUTF(creatSumJson(a, b));
                    } else {
                        JSONObject jo = new JSONObject(data);
                        int a = jo.getInt("data");
                        for (int i = 0; i < 100; i++) {
                            a++;
                            dos.writeUTF(createRandomJson(a));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                dis.close(); dos.close(); s.close();
                System.out.print("鏈接已斷開");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    public static String createRandomJson(int a) {
        JSONObject s = new JSONObject();
        try {
            s.put("data", a);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    public static String creatSumJson(int a, int b) {
        JSONObject s = new JSONObject();
        try {
            s.put("sum", a + b);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return s.toString();
    }
}

就這樣搞定,run!

四、踩到的坑與幾點反思

關於 JSON 套件:Android 環境自帶 json 的 jar 包,但純 JDK 沒有,得自己匯入。我最初是在 Android Studio 裡寫的,一執行就拋異常,log 裡的關鍵字是「stub」;匯入了 json 套件後還是報錯,最後換到 IDEA、正確掛上 json 套件才跑通。

關於這個「一 thread 一 client」的模型:它足以應付練習與中小型連線數,但缺點也很明顯——連線一多,執行緒數量會直線上升,記憶體與上下文切換成本吃不消。真實專案通常會往兩個方向調整:一是改用執行緒池(ExecutorService)來重用執行緒,避免無限擴張;二是直接換成 NIO(Selector 多路複用)或 Netty 這類框架,用少量執行緒撐起大量連線。

還少了幾件事:

  • 沒有心跳機制,客戶端異常斷線時伺服器只能靠讀取超時或例外被動發現。
  • DataOutputStream/DataInputStream 每次迴圈重新 new 一次其實沒必要,提到迴圈外即可。
  • 用 data.contains("data") 來判斷接口類型太脆弱,實務上應該用明確的 type 欄位或指令碼來路由。
  • 資源釋放建議改用 try-with-resources,避免例外路徑漏關。

從單客戶端到多客戶端,改動其實只有一個 while 迴圈加上一個執行緒,但背後的思維轉變才是重點:伺服器的職責是「接」與「派」,而不是「處理」。

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