views:

788

answers:

2

It seems to me that there is some kind of limitation in socket creation in MIDP. I need to make lots of connections to a server (none concourrent) and in the forth or fith try my app crashes. It crashes in the simulator and in my real device as well.

To isolate any possibility of it being influenced 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 crashes in the 13th try.

I've tryed to add a sleep of 10 seconds inside a while loop and, it crashes at the 13th try too.

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
+3  A: 

While c.close() inside the try should be adequate, I am wondering if you have other issues that are triggering this. The code really should be closing the connection AND inputstream inside of a 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!"); 
    }
  }
}
jsight
A: 

The reason, why the c.close() did not actually close was because the inputstream was not closed. Some devices require that both the stream and the connection be closed. Also the connections do not close immediately, on some devices, when the close() method is called. You might have to do a gc too

Ram