編輯:關於 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 欄位或指令碼來路由。從單客戶端到多客戶端,改動其實只有一個 while 迴圈加上一個執行緒,但背後的思維轉變才是重點:伺服器的職責是「接」與「派」,而不是「處理」。
Android 入門實作:打造一個文件夾管理器(一)主體架構與列表呈現
我們手上的裝置通常都自帶廠商開發的檔案管理、相機等系統應用。今天要動手做的,是一個入門級的文件夾管理器。 整個專案大約六個類別,不摻雜任何外部服務,就是一個純粹的本地檔案
Android 開發技巧(2):登入與註冊模組的完整解決方案
前言 幾乎每個 App 都有登入與註冊。以筆者開發的「南方周末新聞閱讀器」為例,個人中心裡就有登入、手機註冊、忘記密碼三個入口。這個模組外觀看起來平平無奇,真要做得好卻要
Android 答題器翻頁:用 ViewFlipper 搭配手勢判斷
本文分享一個答題器的翻頁功能,做法是 ViewFlipper 加 GestureDetector 的組合,供參考。1. 效果2. 思路把 Activity 的觸控事件全部
Android 效能分析利器:Systrace 介紹與使用
一、簡介 Systrace 是 Android 4.1 開始引入的一套管線式效能分析工具。它建立在 Linux 核心的 ftrace 機制之上(ftrace 主要用於追蹤