在我看来,在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次尝试时崩溃。
我尝试在while循环中添加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发布于 2009-07-22 19:49:50
虽然try中的c.close()应该就足够了,但我想知道是否有其他问题触发了这一点。代码真的应该在finally中关闭连接和输入流。如下所示:
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!");
}
}
}发布于 2009-08-03 06:02:17
c.close()实际上没有关闭的原因是因为输入流没有关闭。某些设备要求同时关闭流和连接。此外,在某些设备上,当调用close()方法时,连接不会立即关闭。您可能还需要做gc
https://stackoverflow.com/questions/1167636
复制相似问题