I created a class called ConnectionManager that is basically a wrapper around a connection object. Anytime anything wants to make a connection they get the object from the ConnectionManager. If the connection ever times out you can just call ConnectionManager.reset() to reset the object.
Code:
public class ConnectionManager
{
private static SocketConnection connection = null;
private static DataOutputStream output = null;
private static DataInputStream input = null;
private String url;
public ConnectionManager (String url)
{
this.url = url;
}
public SocketConnection getConnection ()
{
if (connection == null)
{
try
{
// setup our connection to the DNS
connection = (SocketConnection) Connector.open( url, Connector.READ_WRITE, true );
// disable keep alive
connection.setSocketOption( SocketConnection.KEEPALIVE, 0 );
// disable linger
connection.setSocketOption( SocketConnection.LINGER, 0 );
}
catch (final IOException e)
{
this.reset();
return getConnection();
}
}
return connection;
}
public DataOutputStream getDataOutputStream ()
{
if (output == null)
{
try
{
output = getConnection().openDataOutputStream();
}
catch (final IOException e)
{
this.reset();
return getDataOutputStream();
}
}
return output;
}
public DataInputStream getDataInputStream ()
{
if (input == null)
{
try
{
input = getConnection().openDataInputStream();
}
catch (final IOException e)
{
this.reset();
return getDataInputStream();
}
}
return input;
}
public void reset ()
{
try
{
input.close();
}
catch (IOException e)
{
// no concern, we want to close it anyway
}
input = null;
try
{
output.close();
}
catch (IOException e)
{
// no concern, we want to close it anyway
}
output = null;
try
{
connection.close();
}
catch (IOException e)
{
// no concern, we want to close it anyway
}
connection = null;
}
}
You have to make sure you don't access the connection from multiple threads at the same time though!
Hope that helps