Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
New Developer
Posts: 5
Registered: ‎01-12-2009
My Device: Not Specified

Random ConnectionClosedException's

[ Edited ]

Hello, my app is getting random ConnectionClosedException's and I am not sure why. I have created a minimal test app that reproduces my problem:

 

import javax.microedition.io.*;
import java.io.*;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.crypto.tls.tls10.*;
import net.rim.device.cldc.io.ssl.TLSException;

public class Test extends UiApplication {
    Test() {
        pushScreen(new TestScreen());
    }
    
    public static void main(String[] args) {
        new Test().enterEventDispatcher();
    }
}

class TestScreen extends MainScreen {
    public TestScreen() {
        setTitle("testing");
        new Thread(new Runnable() {
            public void run() {
                try {
                    testingPOST();
                } catch(final Exception e){
                    UiApplication.getUiApplication().invokeLater( new Runnable() {
                        public void run() {
                            Dialog.alert(e.toString());
                        }
                    });                    
                }
            }
        }).start();
    }
    
   
    public void testingPOST() throws IOException, TLSException {
        StreamConnection conn = (StreamConnection) Connector.open("ssl://web.myserver.me:443;deviceside=true;EndToEndRequired=true");
        final OutputStream out = conn.openOutputStream();
        
        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"><soap:Body><ConnectivityTest xmlns=\"http://tempuri.org/\" /></soap:Body></soap:Envelope>";
        
        StringBuffer obuff = new StringBuffer();
        obuff.append("POST /services/services.asmx HTTP/1.1\r\n");
        obuff.append("Host: web.myserver.me:443\r\n");
        obuff.append("Content-Length: " + xml.length() + "\r\n");
        obuff.append("Connection: close\r\n");
        obuff.append("Content-Type: application/soap+xml; charset=utf-8\r\n");        
        obuff.append("User-Agent: MyApp 1.0\r\n");
        obuff.append("\r\n");
        obuff.append(xml);
        
        out.write(obuff.toString().getBytes());
        out.flush();
        
        System.out.println(obuff.toString());
        
        final InputStream inputstream = conn.openInputStream();
        
        int c = 0;
        final StringBuffer buf = new StringBuffer();
        while((c = inputstream.read()) != -1) {
            buf.append((char) c);
        }
        UiApplication.getUiApplication().invokeLater( new Runnable() {
            public void run() {
                Dialog.alert(buf.toString());
            }
        });

        conn.close();
    }
}

 

The problem I am having is that the connection randomly seems to close before I can read the inputsteream in the while loop. Half of the time it works fine and I am able to see the response, half of the time I get ConnectionClosedException. I am pretty pussled, what am I doing wrong? I am using JDE 4.7.0. Reproducable in the simulator.

 

Thanks,

Developer
Posts: 1,474
Registered: ‎04-14-2009
My Device: Not Specified

Re: Random ConnectionClosedException's

(in no particular order)

 

1. Check the log of your server, especially the TLS/SSL layer to see how this issue looks like from the server's perspective.

 

2. Try using tls:// instead of ssl://

 

3. Try opening (no need to read though) the input stream before you open the output stream.

 

4. Inspect the Event Log to see whether the connection goes via the WAP APN or via the internet TCP APN (the one specified in Options -> Advanced Options -> TCP). (You should see entries like net.rim.tunnel - Open-<APN>, and net.rim.tunnel - STac-<APN>). WAP gateways cause the ConnectionClosedException much more often.

 

5. Check how long it takes to establish the TLS/SSL connection (i.e., how long it takes to execute Connector.open). May be it takes suspiciously long (e.g., 40 seconds).

 

6. Try routing the connection via WiFi (append ;interface=wifi to the Connector.open URL) to control for carrier network issues.

Developer
Posts: 1,474
Registered: ‎04-14-2009
My Device: Not Specified

Re: Random ConnectionClosedException's

P.S. There's a bug in your handling of the HTTP request body/payload. The Content-Length header specifies the lengh of the body in bytes, whereas your code sets it as the length in Java characters. The Content-Type header specifies the character encoding of the body as UTF-8, whereas your code happily sends the body in the platform default encoding (which is typically ISO-8859-1 or US-ASCII). As a result, your server-side code may not be able to correctly convert the read body bytes into an array of Unicode characters or a Java string if your XML payload contains at least one non-ASCII character or a zero-character. Also, if the platform encoding turns out to be UTF-8 or some other encoding that encodes some characters using multiple bytes, then your code will send a request where Content-Length will not match the actual length and the server-side code may block indefinitely or go out of sync with the client-side.

Developer
Posts: 151
Registered: ‎03-27-2009
My Device: Not Specified

Re: Random ConnectionClosedException's

I've also been noticing "Random ConnectionClosedExceptions". I have done a lot of code debugging as well as packet sniffing and have pinned down the cause of my exceptions. Unfortunately my fix is not ideal, and I'm not sure that it will hold up.

 

To start off, here's the basics of my connection routine:

 

connectionString += ";deviceside=true"; // we're doing DIRECT TCP here

httpConnection = (HttpConnection) Connector.open(connectionString);
httpConnection.setRequestProperty("x-rim-transcode-content", "none"); // i read this prevents proxies from messing with your data
httpConnection.setRequestMethod(HttpConnection.GET);

inputStream = httpConnection.openInputStream();

int len = (int) httpConnection.getLength();
if (len > 0) {
    int actual = 0;
    int bytesread = 0;
    byte[] data = new byte[len];
    while ((bytesread != len) && (actual != -1)) {
        actual = inputStream.read(data, bytesread, len - bytesread);
        bytesread += actual;
    }
    byteArrayOutputStream.write(data);
} else {
    try {
        while ((len = inputStream.read(buffer)) != -1) {
            Logger.log("reading length[" + len + "] of " + connectionString);
            byteArrayOutputStream.write(buffer, 0, len);
        }
    } catch (ConnectionClosedException e) {Logger.log("ignoring connection closed exception");}
}

 

 

I put the try block in because an exception is randomly thrown when inputstream.read(byte[]) is called. The incredible thing is that this exception is only thrown when 'read' should be returning -1, ie. I have all the data I need anyways, so it doesn't matter. 

 

And it is random from my view: I've sniffed the request/responses for two identical requests, one which threw the exception and one which didn't (this is all in the simulator). The requests and responses are exactly the same, and look something like this:

 

 

GET MYURL HTTP/1.1

Host: MYHOST:8080

Connection: close

x-rim-transcode-content: none



HTTP/1.1 200 OK

Server: Apache-Coyote/1.1

Content-Type: application/json;charset=UTF-8

Date: Thu, 29 Oct 2009 19:55:50 GMT

Connection: close



{a bunch of JSON}

 

 

If I worked for RIM and had to guess, I would say that there is some asynchronous underlying networking components that are working out of order on occasion and somehow the connection.close signal is affecting my inputstream from being able to return -1 on a read. Just a guess..

 

This is running on the following simulator:

Blackberry 9500

v5.0.0.224 (Platform)

 

 

New Developer
Posts: 39
Registered: ‎10-13-2009
My Device: Not Specified

Re: Random ConnectionClosedException's

I'm facing the same problem when I call socketconnection.openInputStream().

Did u guys get a solution for it?

 

JDE 4.3.0

Device Simulator 9700 (5.0.0.228) and other 5.0 OS devices

Highlighted
Contributor
Posts: 34
Registered: ‎07-05-2011
My Device: Various
My Carrier: Generic

Re: Random ConnectionClosedException's

I think I'm going to break down and cry....

This post is apparently back in 2009 - with no solid resolution.

 

And here I sit, with pretty much similiar problems...and no solution in sight.

 

My problems seem to be centered arount the use of  SSL (perfectly valid, Thwate signed cert).

The fun bit is it works FINE on a simulator, but I can't get an open input stream on the device, even though I can SEE the request hitting the server (and the server responding).

 

Truly, not a fun two days for me.