Ric*_*ras 3 java sockets midp java-me
在我看来,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();
}
Run Code Online (Sandbox Code Playgroud)
这段代码在第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
Run Code Online (Sandbox Code Playgroud)
虽然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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)