1

How can I detect when a java socket (client socket or server socket) is closed & execute a callback method when close event occurs? I don't want to use exception handling to do this. I'm seeking for a solution such as event handler or callback method, something like this(this is just an imaginary code!) :

Socket s = new Socket(ip, port);
s.addSocketClosedHandler(new SocketClosedHandler(){

    @Override
    public void onSocketClosed(SocketClosedEvent e){
        ...
    }

});

2 Answers 2

2

Do you want to handle the event that you close the socket or the event that 'the other side' closes the socket? In the first case, you could subclass Socket and add handlers called when you call 'close'.

In the latter case, the problem is that this is not automatically detected and that reliably detecting it can be difficult and depends on the protocol being used to communicate over the socket. See e.g. this SO question. In general you will have to take action to determine whether the socket has in fact been closed by the other side. If so, you will need to take action. Whatever action you take, you could make sure it also calls callback handlers you registered for that action.

0

Why can't you use exception handling? This is the way the API is designed.

The only other way to do this is to design your protocol so that the other side sends something before it is about to close so that a local call to close() can be made first - but this won't always work, such as if the connection is closed unexpectedly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.