Java – MIDP limited sockets?
•
Java
In my opinion, there are some restrictions on socket creation in MIDP
In order to isolate any possibility that it is affected by my code, I isolated the following code:
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(); }
This code crashed on the 13th attempt
I tried to add a 10 second sleep to a while loop, and it crashed on the 13th attempt
The crash message is:
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
Solution
Although c.close () in try should be enough, I wonder if you have any other problems that trigger this problem The code should really close the connection and input stream in finally Something like this:
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!"); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码