J2ME (Java 2 Micro Edition) 專為消費類電子設備(手機、PDA、機頂盒等)設計,提供基於 HTTP 的高級網絡協議支持,使移動設備能以 Client/Server 模式訪問互聯網資源。掌握 J2ME 網絡編程是開發無線移動應用的關鍵。
https://127.0.0.1:8080 顯示歡迎頁面即成功。/515game,映射到本地目錄 D:/mygameWeb。此后可通過 https://IP:8080/515game/資源名 訪問資源。J2ME 將網絡操作封裝在 javax.microedition.io 包中,核心是 Connector.open(url) 獲取 StreamConnection,再通過 openInputStream() 讀取數據。
String url = "https://127.0.0.1/515game/myweb.html";
StreamConnection sc = (StreamConnection) Connector.open(url);
InputStream is = sc.openInputStream();
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = is.read()) != -1) sb.append((char) ch);
is.close(); sc.close();
// 處理中文編碼
String result = new String(sb.toString().getBytes("ISO-8859-1"), "UTF-8");
String url = "https://127.0.0.1/515game/back0.png";
StreamConnection sc = (StreamConnection) Connector.open(url);
InputStream is = sc.openInputStream();
Image img = Image.createImage(is); // MIDP 2.0 方法
Form form = new Form("圖片");
form.append(img);
Display.getDisplay(this).setCurrent(form);
sc.close();
String url = "https://127.0.0.1/515game/kk.wav";
StreamConnection sc = (StreamConnection) Connector.open(url);
InputStream is = sc.openInputStream();
Player player = Manager.createPlayer(is, "audio/x-wav");
player.start();
sc.close();
服務端 (checkuser.jsp):接收 username/password 參數,驗證後輸出結果。
客戶端:構建登錄表單,用戶點擊確定後啟動線程發送 GET 請求 checkuser.jsp?username=...&password=...,讀取響應並顯示結果。
服務端 (Guess.jsp):生成 0-9 隨機數,比對用戶提交的價格參數 jg,返回 "right"、"sorry da le" 或 "sorry xiao le"。
客戶端:輸入價格發送請求 Guess.jsp?jg=...,解析響應顯示競猜結果,提供"返回"按鈕重新遊戲。
new String(bytes, "ISO-8859-1"), "GBK/UTF-8")。