views:

247

answers:

2

My chat application connects to a server and information is sent/received by the user. When the connection changes, such as 3g->wifi, wifi->3g, losing a data connection, etc, the socket sometimes stays connected for ages before disconnecting. During this time, it's impossible to tell if the connection is still active, it seems as if messages are being sent just fine. Other times, when sending a message, it will throw an IO error and disconnect.

Apart from implementing code to detect connection changes and reconnecting appropriately, is it possible to have the socket immediately throw an IO exception when connectivity changes?

Edit: I'm connecting using the following code:

Socket sock = new Socket();
sock.connect(new InetSocketAddress(getAddress(), getPort())), getTimeout());
//get bufferedReader and read until BufferedReader#readLine() returns null

I'm not using setSoTimeout as data may not be transferred for long periods of time depending on the remote server's configuration.

+1  A: 

Are you talking about a java.net.Socket connection? Then try setSoTimeout(). Otherwise specify how you're connecting.

Mirko Nasato
A: 

This is an old problem that I've seen a few times before in the database world.

The solution I used there was to manage the connection at the application level. I'd explicitly send a no-op message of some sort (i.e. SELECT 1 WHERE FALSE) over the connection every so often as a ping, and if this failed I would tear down and re-establish the connection, possibly to a failover server if the original wasn't accepting connections.

Kevin Wright