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

Android Socket 通信實戰:打造可互傳 JSON 的服務端與客戶端

編輯:關於 Android 程式設計

本文示範如何在兩台 Android 裝置之間,透過 Socket 建立連線並互傳資料,並以 JSON 作為通訊格式。範例包含一個服務端與一個客戶端,雙方約定使用同一個連接埠(30000),並示範傳送單個資料、多個資料與嵌套 JSON 陣列三種情境。

一、服務端

服務端負責開啟 ServerSocket 監聽連線,接收客戶端資料、解析 JSON,並回傳結果。介面上顯示本機 IP 與連線情況。核心邏輯如下:

public class MainActivity extends Activity {
    public static ServerSocket serverSocket = null;
    public static TextView mTextView, textView1;
    private String IP = "";
    String buffer = "";

    public static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                mTextView.append("客戶端:" + bundle.getString("msg") + "\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        mTextView = (TextView) findViewById(R.id.textsss);
        textView1 = (TextView) findViewById(R.id.textView1);
        IP = getIp();
        textView1.setText("IP addresss:" + IP);

        new Thread() {
            public void run() {
                Bundle bundle = new Bundle();
                bundle.clear();
                OutputStream output;
                String str = "通信成功";
                try {
                    serverSocket = new ServerSocket(30000);
                    while (true) {
                        Message msg = new Message();
                        msg.what = 0x11;
                        try {
                            Socket socket = serverSocket.accept();
                            output = socket.getOutputStream();
                            // 注意資料流編碼,雙端一致時避免亂碼
                            output.write(str.getBytes());
                            output.flush();
                            socket.shutdownOutput();
                            BufferedReader bff = new BufferedReader(
                                    new InputStreamReader(socket.getInputStream()));
                            String line = null;
                            buffer = "";
                            while ((line = bff.readLine()) != null) {
                                if (!parseJsonMulti(line).equals("")) line = parseJsonMulti(line);
                                buffer = line + buffer;
                            }
                            bundle.putString("msg", buffer.toString());
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);
                            bff.close();
                            output.close();
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }.start();
    }
    // parseJsonMulti()、getIp() 等方法參見下方說明
}

其中 parseJsonMulti() 負責解析 JSON,根據 Type 欄位判斷是「單個數據」「多個數據」還是「嵌套 JSON 數組」,並提取對應的值;getIp() 則同時兼顧 WiFi 與非 WiFi 情境來取得本機 IP。

private String parseJsonMulti(final String strResult) {
    String result = "";
    try {
        JSONObject json_data = new JSONObject(strResult);
        String Type = json_data.getString("Type");
        if (Type.equals("單個數據")) {
            result = Type;
        } else if (Type.equals("多個數據")) {
            String NUM = json_data.getString("NUM");
            result = Type + " " + NUM;
        } else if (Type.equals("嵌套JSON數組")) {
            JSONArray Array = json_data.getJSONArray("Array");
            JSONObject OneObject = Array.getJSONObject(0);
            JSONObject TwoObject = Array.getJSONObject(1);
            result = OneObject.getInt("one") + " 參數 " + TwoObject.getInt("two");
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return result;
}

/** 取得本機 IP(WiFi 或非 WiFi 均適用) */
public String getIp() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        return getLocalIpAddress();
    }
    return intToIp(wifi_ip(wifiManager));
}

/** 將(16 進制)IP 轉為點分十進制 */
private String intToIp(int i) {
    return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "."
            + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
}

二、客戶端

客戶端透過 Socket 連上服務端 IP,發送 JSON 資料並接收回傳。介面提供多個按鈕,分別對應單個、多個與嵌套 JSON 陣列的傳輸情境。

public class MainActivity extends Activity implements OnClickListener {
    Socket socket = null;
    String buffer = "";
    TextView Msg;
    EditText ed_msg;
    String io_msg;

    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                Bundle bundle = msg.getData();
                Msg.append("server:" + bundle.getString("msg") + "\n");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Msg = (TextView) findViewById(R.id.msg);
        ed_msg = (EditText) findViewById(R.id.ed_msg);
        findViewById(R.id.send).setOnClickListener(v -> {
            io_msg = ed_msg.getText().toString();
            new SendThread(io_msg, getIp()).start();
        });
        findViewById(R.id.single).setOnClickListener(this);
        findViewById(R.id.multiple).setOnClickListener(this);
        findViewById(R.id.nested).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.single:
                    JSONObject o1 = new JSONObject();
                    o1.put("Type", "單個數據");
                    Sendmsg(o1.toString());
                    break;
                case R.id.multiple:
                    JSONObject o2 = new JSONObject();
                    o2.put("Type", "多個數據");
                    o2.put("NUM", "號碼");
                    Sendmsg(o2.toString());
                    break;
                case R.id.nested:
                    JSONObject One = new JSONObject();
                    One.put("one", "3");
                    JSONObject Two = new JSONObject();
                    Two.put("two", "8");
                    JSONArray arr = new JSONArray();
                    arr.put(One);
                    arr.put(Two);
                    JSONObject o3 = new JSONObject();
                    o3.put("Type", "嵌套JSON數組");
                    o3.put("Array", arr);
                    Sendmsg(o3.toString());
                    break;
            }
        } catch (JSONException e) {
            Toast.makeText(this, "發送失敗!JSON異常", Toast.LENGTH_SHORT).show();
        }
    }

    // 負責建立連線、收發資料的工作執行緒
    class SendThread extends Thread {
        public String Ip, str;
        public SendThread(String _str, String _Ip) { str = _str; Ip = _Ip; }

        @Override
        public void run() {
            Message msg = new Message();
            msg.what = 0x11;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(Ip, 30000), 5000); // 逾時 5 秒
                OutputStream ou = socket.getOutputStream();
                BufferedReader bff = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                String line = null;
                buffer = "";
                while ((line = bff.readLine()) != null) {
                    buffer = line + buffer;
                }
                ou.write(str.getBytes());
                ou.flush();
                bundle.putString("msg", buffer.toString());
                msg.setData(bundle);
                myHandler.sendMessage(msg);
                bff.close();
                ou.close();
                socket.close();
            } catch (SocketTimeoutException aa) {
                bundle.putString("msg", "服務器連接失敗!請檢查網絡是否打開");
                msg.setData(bundle);
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // getIp()、getLocalIpAddress()、intToIp() 與服務端相同
}

三、注意事項

實作這類 Socket 通信時,有幾個容易踩雷的點值得留意:

  • 編碼一致:服務端與客戶端的資料流編碼必須相同,否則容易出現亂碼。
  • 避免主執行緒阻塞:網路 I/O 一定要放在子執行緒中,並透過 Handler 更新 UI。
  • 連接逾時:為連線設定合理的逾時時間,並針對逾時、連線失敗等情境給出友善提示。
  • 權限:別忘了在 AndroidManifest.xml 中加入 INTERNET 權限,並注意 Android 9.0 以上對明文流量的限制。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved