編輯:關於 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 通信時,有幾個容易踩雷的點值得留意:
INTERNET 權限,並注意 Android 9.0 以上對明文流量的限制。
[Android 開發系列] 動手做一個 IT 博客聚合瀏覽器
1. 先談談那個「坑」 坦白說,這篇之前欠下的帳有點多。先前開頭的兩個 Android 開發教學系列,寫到後面實在提不起勁,就先擱著了,這裡說聲抱歉。不過原始碼都有放在
Android 筆記(四):Fragment 的基本用法與 Activity 通訊
前置說明一:照前面的方式建立專案時,如果用的是較新的 ADT,而 Minimum SDK 選了 Android 2.* 或 1.*,系統會自動產生一個相容用的附屬專案 a
Android Activity 四種啟動模式解析
Activity 是 Android 應用中最重要的元件之一。當應用程式運行時,Activity 會被放入任務堆疊中,而不同的啟動模式會影響 Activity 的建立與重
Eclipse Indigo 與 ibus 衝突問題分析:Android 開發環境實錄
今天在筆記型電腦上開發時又碰到了老問題。經過反覆確認,Eclipse Indigo 版本與 ibus 1.3.11 之間確實存在衝突。具體表現是:在 Eclipse 編輯