2.2.3 使用套接字連線
雖然你可以通過套接字連線來實現HTTP,但由於如下原因,你應該使用HTTP連線:
> 套接字連線不支援黑莓移動資料系統(MDS)的特色功能,例如推送.
> 使用套接字連線的黑莓裝置應用程式通常比使用HTTP連線的黑莓裝置應用程式需要更多的頻寬
BlackBerry® device applications that use socket connections typically require significantly more bandwidth than BlackBerry device applications that use HTTP connections.
1. 匯入如下類:
* net.rim.device.api.system.CoverageInfo
* javax.microedition.io.Connector
* java.lang.String
* java.io.OutputStreamWriter
* java.io.InputStreamReader
2. 匯入如下介面:
* net.rim.device.api.system.CoverageStatusListener
* javax.microedition.io.StreamConnection
3. 使用net.rim.device.api.system包中的CoverageInfo類和CoverageStatusListener介面來確認黑莓裝置在無線網路覆蓋區域內。
4. 呼叫Connector.open(),指定socket為協議,並將引數deviceside=false附在URL的末端
* 為使用黑莓MDS服務開啟套接字連線,將deviceside=false附於URL末端。黑莓裝置應用程式必須明確的輸入本地主機IP,因為localhost是不被支援的。
private static String URL = "socket://local_machine_IP:4444;deviceside=false";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
* 為通過直接TCP來開啟套接字連線,將引數deviceside=true附於URL末端。
private static String URL = "socket://local_machine_IP:4444;deviceside=true";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
* 為通過直接TCP來開啟套接字連線,指定APN資訊,將引數deviceside=true附於URL末端,並指定將在其之上建立連線的APN。指定連結到APN的使用者名稱和密碼(如果APN需要密碼)。
private static String URL = "socket:
//local_machine_IP:4444;deviceside=true;apn=internet.com;tunnelauthusername =user165;tunnelauthpassword=user165password";
StreamConnection conn = null;
conn = (StreamConnection)Connector.open(URL);
5. 使用 openInputStream() 和 openOutputStream() 來發送和接受資料。
OutputStreamWriter _out = new OutputStreamWriter(conn.openOutputStream());
String data = "This is a test";
int length = data.length();
_out.write(data, 0, length);
InputStreamReader _in = new InputStreamReader(conn.openInputStream());
char[] input = new char[length];
for ( int i = 0; i < length; ++i ) {
input[i] = (char)_in.read();
};
6. 在輸入流、輸出流和套接字連線上呼叫close()。每個close()都可能丟擲IOException。確保黑莓裝置應用程式實現了異常處理。
_in.close();
_out.close();
conn.close();