J2ME 網絡開發主流採用 HTTP(請求/響應)與 Socket(長連接/雙向流)兩種模式。本文提供雙模式完整客戶端/伺服器端代碼範例,並分析適用場景與 GPRS 環境下的注意事項。
客戶端 GET 請求:
public String requestGET(String baseUrl, String params) throws IOException {
HttpConnection hpc = null; DataInputStream dis = null;
try {
hpc = (HttpConnection) Connector.open(baseUrl + params);
hpc.setRequestMethod(HttpConnection.GET);
dis = new DataInputStream(hpc.openInputStream());
StringBuilder sb = new StringBuilder();
int ch; boolean esc = false;
while ((ch = dis.read()) != -1) {
if (esc) { if (ch == 'n') sb.append('\n'); else sb.append('\\').append((char)ch); esc = false; }
else if (ch == '\\') esc = true;
else sb.append((char)ch);
}
// 中文轉碼:ISO8859_1 -> GB2312
return new String(sb.toString().getBytes("ISO8859_1"), "GB2312").trim();
} finally {
if (dis != null) dis.close();
if (hpc != null) hpc.close();
}
}
伺服器端:普通 JSP/Servlet 接收參數,輸出文本/JSON/XML 即可,無特殊要求。
客戶端連接與收發:
// 連接
StreamConnection conn = (StreamConnection) Connector.open("socket://192.168.0.1:6666");
// 發送
OutputStream os = conn.openOutputStream(); os.write(data); os.flush(); os.close();
// 接收
InputStream is = conn.openInputStream(); /* 讀取回應 */ is.close();
conn.close();
伺服器端(Java SE):
ServerSocket server = new ServerSocket(6666);
while (true) {
Socket client = server.accept();
new Thread(() -> {
try {
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
// 讀取請求、寫入響應
} finally { client.close(); }
}).start();
}
| 場景 | 推薦模式 | 理由 |
|---|---|---|
| 簡單數據查詢、表單提交、REST API | HTTP | 穿透防火牆/代理能力強、無狀態、易調試 |
| 即時聊天、多人遊戲、推送通知 | Socket | 低延遲、雙向流、支持自定義協議 |
| 二進制大文件上傳/下載 | HTTP (POST/Chunked) 或 Socket | 視伺服器端支援而定 |