2009-07-22 49 views
3

在我看來,在MIDP中創建套接字時存在某種限制。 我需要與服務器建立大量連接(不是concourrent),並在第四步或者第五步嘗試我的應用程序崩潰。它在模擬器和我真實的設備中崩潰。midp有限的插座?

要隔離它是由我的代碼影響的任何可能性,我孤立下面的代碼:

try { 
     StreamConnection c; 
     StringBuffer sb = new StringBuffer(); 
     c = (StreamConnection) Connector.open(
      "http://www.cnn.com.br/", Connector.READ_WRITE); 
     InputStreamReader r = new InputStreamReader(c.openInputStream(), "UTF-8"); 
     System.out.println(r.read()); 
     c.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 

此代碼崩潰在13嘗試。

我tryed加10秒的睡眠,同時循環內,並且,它崩潰在13日嘗試過。

崩潰的消息是:

java.io.IOException: Resource limit exceeded for TCP client sockets 
- com.sun.midp.io.j2me.socket.Protocol.open0(), bci=0 
- com.sun.midp.io.j2me.socket.Protocol.connect(), bci=124 
- com.sun.midp.io.j2me.socket.Protocol.open(), bci=125 

回答

7

雖然c.close()在try裏面應該是足夠的,我如果您有此引發的其他問題疑惑。該代碼真的應該關閉連接和輸入流內的一個最後。像這樣:

StreamConnection c = null; 
InputStream is = null; 
try { 
    StringBuffer sb = new StringBuffer(); 
    c = (StreamConnection) Connector.open(
     "http://www.cnn.com.br/", Connector.READ_WRITE); 
    is = c.openInputStream(); 
    InputStreamReader r = new InputStreamReader(is, "UTF-8"); 
    System.out.println(r.read()); 
} catch (IOException ex) { 
    ex.printStackTrace(); 
} finally { 
    if (is != null) { 
    try { 
     is.close(); 
    } catch (Exception ex) { 
     System.out.println("Failed to close is!"); 
    } 
    } 
    if (c != null) { 
    try { 
     c.close(); 
    } catch (Exception ex) { 
     System.out.println("Failed to close conn!"); 
    } 
    } 
} 
0

原因,爲什麼c.close()沒有真正關閉是因爲輸入流未關閉。某些設備要求關閉流和連接。此外,在調用close()方法時,某些設備上的連接不會立即關閉。您可能需要做一個GC太