views:

482

answers:

2

Hi,

I can't find in the socket java API a way to close a inactive connection open for TIMEOUT millisecond. The goal is to avoid an embarassing error when I forget to close the socket explicitly (and force the distant resource to be rebooted).

If I don't find a low level method, I will add a last-time-used value to our connection, and check it periodically... but I find that ugly.

Thanks,

Antoine

P.S. I don't want the connection timeout, and I'm not sure to understand the setSoTimeout, but I'm quite sure it's not what we want.

P.P.S. Sure, avoid to forget the close is better, but in a big project + big teams...we try to find a 100% secure way.

A: 

Hi,

maybe, you can create a Socket Wrapper that or an Observer for use when you initialize a Socket instance.

With Aspcts (AOP), you can intercept all your Socket creation calls as pointcuts, and start a new TimeoutObserver as an Aspect.

This TimeoutObserver contains implemention for your own rules to check if the socket are opened or closed.

An advantage f that solution, is the not intrusive AOP model, when you are safe about the already implemented and new implementations in your corporative software.

Maybe, thats a way to treat that question.

[]'s,

apast
+1  A: 

Try turning on SO_KEEPALIVE:

s.setKeepAlive(true);

With keep alive set the client should occasionally (commonly one or two hours) send a test packet back to your server. If it doesn't receive a response with in some number of minutes it will assume the server has closed the connection with out notifying it and will close itself.

That should work in case your server crashes at any rate. I'm not sure if it will work if your server's still running - just ignoring the client.

It would be far, far better just to keep track of all the sockets you create and have a thread periodically check each one to see if it's still open and has been used recently. I don't think that's ugly, I think it's probably the best way to handle this.

Daniel Bingham
Yep. Sorta difficult to arrive at any robust solution that is exposed on a team effort - since I code indie my first design arrives at run(){ do { catch timeout exception; ) while ( stayRunning );}with stayRunning as a public staticTracking all the sockets and so on gets sync() issues but as you say, it's not ugly.
Nicholas Jordan