首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

J2ME GCF 通用連接框架深度解析:接口體系與最佳實踐

     編輯:J2ME

前言:GCF 是 J2ME 網絡編程的基石

Generic Connection Framework (GCF) 定義於 CLDC,因移動設備資源受限,標準 java.net/java.io 過於龐大不適用。GCF 以接口導向設計、工廠模式創建連接、標準 URL 統一寻址三大特征,優雅解決了協議多樣性與資源約束的矛盾。

GCF 接口繼承體系全景

Connection (頂層接口,唯一方法 close())
├── StreamConnection (流連接,雙向)
│   ├── InputConnection (輸入流) → openInputStream()
│   ├── OutputConnection (輸出流) → openOutputStream()
│   ├── ContentConnection (內容屬性) → getType()/getEncoding()/getLength()
│   │   └── HttpConnection (HTTP 協議) → GET/POST/HEAD, 標頭管理, 響應碼
│   │       └── HttpsConnection (HTTPS, MIDP 2.0)
│   ├── StreamConnectionNotifier (服務端監聽) → acceptAndOpen()
│   │   └── ServerSocketConnection (TCP Server) → socket://:port
│   └── SocketConnection (TCP Client) → socket://host:port
├── DatagramConnection (數據報)
│   └── UDPDatagramConnection (UDP) → datagram://host:port
└── CommConnection (串口, 不做重點)

核心接口方法速查

統一入口:Connector.open() URL 格式規範

格式:{scheme}:[{target}][{params}] (參考 RFC 2396)

接口關鍵方法用途
Connectionclose()統一資源釋放入口
InputConnectionopenInputStream()獲取輸入流
OutputConnectionopenOutputStream()獲取輸出流
StreamConnectionNotifieracceptAndOpen()阻塞等待客戶端連接,返回 StreamConnection
ContentConnectiongetType()/getEncoding()/getLength()HTTP 類協議元數據
HttpConnectionsetRequestMethod()/getResponseCode()/getHeaderField()完整 HTTP 客戶端能力
DatagramConnectionnewDatagram()/send()/receive()UDP 無連接通信

實戰代碼模板

1. HTTP GET 請求標準模式


HttpConnection http = null;
InputStream is = null;
try {
    String url = "https://api.example.com/data?param=value";
    http = (HttpConnection) Connector.open(url);
    http.setRequestMethod(HttpConnection.GET);
    http.setRequestProperty("User-Agent", "MyMidlet/1.0");
    http.setRequestProperty("Accept", "application/json");
    
    int rc = http.getResponseCode();
    if (rc == HttpConnection.HTTP_OK) {
        is = http.openInputStream();
        // 讀取數據...
    } else {
        // 錯誤處理
    }
} catch (IOException e) {
    // 網絡異常
} finally {
    if (is != null) try { is.close(); } catch (IOException ignored) {}
    if (http != null) try { http.close(); } catch (IOException ignored) {}
}

2. TCP Socket 客戶端


SocketConnection socket = null;
InputStream is = null; OutputStream os = null;
try {
    socket = (SocketConnection) Connector.open("socket://192.168.1.100:8888");
    socket.setSocketOption(SocketConnection.DELAY, 0); // 關閉 Nagle
    socket.setSocketOption(SocketConnection.LINGER, 5); // 延遲關閉 5s
    
    is = socket.openInputStream();
    os = socket.openOutputStream();
    // 收發數據...
} catch (IOException e) {
} finally {
    // 關閉順序:流先於連接
    if (os != null) try { os.close(); } catch (IOException ignored) {}
    if (is != null) try { is.close(); } catch (IOException ignored) {}
    if (socket != null) try { socket.close(); } catch (IOException ignored) {}
}

3. TCP Socket 服務端 (需簽名權限/特定設備支持)


ServerSocketConnection server = null;
try {
    server = (ServerSocketConnection) Connector.open("socket://:6666");
    while (running) {
        SocketConnection client = (SocketConnection) server.acceptAndOpen();
        // 建議:為每個客戶端啟動獨立線程處理
        new Thread(new ClientHandler(client)).start();
    }
} catch (IOException e) {
} finally {
    if (server != null) try { server.close(); } catch (IOException ignored) {}
}

4. UDP 數據報通信


UDPDatagramConnection udp = null;
try {
    udp = (UDPDatagramConnection) Connector.open("datagram://:5555"); // 綁定本地端口
    Datagram dg = udp.newDatagram(1024); // 緩衝區大小
    
    // 發送
    String msg = "HELLO";
    byte[] data = msg.getBytes();
    Datagram snd = udp.newDatagram(data, data.length, "datagram://192.168.1.100:6666");
    udp.send(snd);
    
    // 接收
    udp.receive(dg); // 阻塞
    String rcv = new String(dg.getData(), 0, dg.getLength());
} catch (IOException e) {
} finally {
    if (udp != null) try { udp.close(); } catch (IOException ignored) {}
}

資源管理鐵律

  1. finally 塊必須關閉:Connection、InputStream、OutputStream、Datagram
  2. 關閉順序:流 → 連接 (反初始化順序)
  3. 異常吞噬:關閉時的 IOException 通常可忽略,記錄日誌即可
  4. 超時設置:HttpConnection 無連接超時 API,需自行實現線程監控

MIDP 2.0 新增 HTTPS 支持

  • HttpsConnection 繼承 HttpConnection,增加 getSecurityInfo() 獲取證書/密鑰信息
  • 設備必須內建根 CA 證書庫,自簽名證書需用戶確認安裝
  • 握手過程顯著增加連接延遲和 CPU 開銷,權衡安全性與性能

設計哲學啟示

GCF 的接口分層、工廠解耦、URL 統一寻址,體現了面向接口編程、依賴倒置、最小知識原則。這種在極約束下的優雅設計,值得所有中間件/框架開發者深入研習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
協議schemetarget 格式示例返回接口類型
HTTPhttp//host:port/path?queryHttpConnection
HTTPShttps//host:port/pathHttpsConnection
TCP Clientsocket//host:portSocketConnection
TCP Serversocket//:port (host 為空)ServerSocketConnection
UDPdatagram//host:portUDPDatagramConnection
文件 (JSR 75)file///path/to/fileFileConnection