J2ME 網路通訊建立在 Generic Connection Framework (GCF) 之上。本文介紹 GCF 核心類別、I/O 流處理,並以「SaveMyMoney 銀行關鍵字查詢」完整實作:從 J2EE 伺服器 HTTP 讀取文字檔、解析每行關鍵字存入 Vector、隨機顯示於手機畫面。
javax.microedition.io (取代 J2SE java.net)。Connector (靜態 open() 建立連線)。ConnectionNotFoundException。Connection、StreamConnection、ContentConnection、DatagramConnection、StreamConnectionNotifier 等。InputStream/OutputStream (套件 java.io)。Reader/Writer。建立 keyword.txt 放置 J2EE 伺服器 public_html 目錄,內容每行一關鍵字說明。
public class SaveMyMoney extends MIDlet implements CommandListener {
private Display display;
private Form form;
private StringItem keyWord;
private Vector keyVector = new Vector();
private Command exitCmd, nextCmd;
public SaveMyMoney() {
display = Display.getDisplay(this);
exitCmd = new Command("Exit", Command.EXIT, 2);
nextCmd = new Command("Next", Command.OK, 2);
form = new Form("SMMB KEYWORDS HELP");
keyWord = new StringItem(" ", "we help");
form.setTicker(new Ticker("want to know your balance... use these keywords to bank with us"));
form.append(keyWord);
form.addCommand(exitCmd);
form.addCommand(nextCmd);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
readKeyword();
showKeyword();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == exitCmd) { destroyApp(false); notifyDestroyed(); }
else if (c == nextCmd) { showKeyword(); }
}
private void readKeyword() {
StreamConnection conn = null;
InputStream in = null;
StringBuffer buf = new StringBuffer();
try {
conn = (StreamConnection) Connector.open("https://localhost:8000/keyword.txt");
in = conn.openInputStream();
int ch;
while ((ch = in.read()) != -1) {
if (ch != ' ') { buf.append((char)ch); }
else { keyVector.addElement(buf.toString()); buf = new StringBuffer(); }
}
} catch (IOException e) {
System.err.println("Connection failed: " + e);
} finally {
try { if (in != null) in.close(); } catch (IOException ignored) {}
try { if (conn != null) conn.close(); } catch (IOException ignored) {}
}
}
private void showKeyword() {
Random rnd = new Random(System.currentTimeMillis());
int pos = Math.abs(rnd.nextInt()) % keyVector.size();
keyWord.setText((String) keyVector.elementAt(pos));
}
}
j2ee -verboseStreamConnection 雙向流。Vector 儲存動態行數,Random 實現隨機抽取。