Friday, October 7, 2011

Forcing Blackberry socket timeout

Maybe if I talk it through I can come up with a better solution because I don't like what I'm doing, but right now, I have nothing better.

Here's the situation.
I've written an application for a Blackberry. This application requires a socket connection to communicate with a remote resource. It works fine, but once in a while I'm told that the application fails to contact the remote server. It throws a connection timeout error, and I'm told that it takes 15 seconds for this to occur. This is not acceptable to the client, and they are requiring that I drive the timeout down to 3 seconds. My research has shown that there is a connection object that will allow me to set a connection timeout, but in order to use this object I have to utilize the BES server. This is not an option, so as far as I can tell, I'm stuck not being able to set a timeout on the connection.

Here's my solution.
I've created a thread object that wraps the process of connecting, sets any exceptions, and sets a boolean variable indicating that the connection attempt is complete. If there's no exception I can assume that a complete connection attempt was successful, and go about my business.
I start the thread.
I then go in to a loop that will loop for 3 seconds or until my boolean variable indicates that my connection is complete. In the loop I sleep for a little bit, and then check again.
I'm not happy with this solution. It feels like there's too much going on with this solution, but I'm just not really sure what else I can do to force the socket to not try to connect for more than 3 seconds.

// something like this.
private static void openConnection(final String url) throws Exception
{
    boolean connecting = true;
    Exception exception = null;

    new Thread()
    {
        public void run()
        {
            try
            {
                _connection = (StreamConnection)Connector.open(url);
            }
            catch(Exception e)
            {
                 _exception = e;
            }
            finally
            {
                 connecting = false;
            }
        }
    }.run();
    long timeout = getTime() + _threadTimeout; // 3000 ms added to the current time
    while(connecting || getTime() < timeout)
    {
        Thread.sleep(50);
    }
    if(null != exception)
    {
        throw exception;
    }
}

No comments:

Post a Comment