Skip to main content

Grizzly : How to be notify when a client disconnect

Posted by survivant on November 25, 2008 at 7:56 AM PST

It's now possible to be notify when a client disconnect for a server build on Grizzly 1.9+.

here a little snippets that will allow you that.  Thanks to the new ConnectionCloseHandler.

public void init(){
        int port = 5000;
        try {
            Controller controller = new Controller();
            TCPSelectorHandler tcpSelectorHandler = new TCPSelectorHandler();
            Pipeline pipeline = new DefaultPipeline();
            BaseSelectionKeyHandler selectionKeyHandler = new BaseSelectionKeyHandler();
            // to be notify when a client close the connection
            selectionKeyHandler.setConnectionCloseHandler(new ConnectionCloseHandler() {

                public void locallyClosed(SelectionKey key) {
                       System.out.println(key + " is being locally cancelled");

                   public void remotlyClosed(SelectionKey key) {
                       System.out.println(key + " is being remotly cancelled (connection closed)");
            ..... add here your protocolChain
      try {
            } catch (IOException e) {
        } catch (Exception e) {

Related Topics >>


Answer from Jean-Francois Arcand. When the remote client close the connection, ConnectionCloseHandler.remotlyClosed() will be invoked *first*, then locallyClosed() will follow. When the framework detect a remote connection closed, it always make sure the SelectionKey is finished properly and eventually invoke SelectionKeyHandler.close(). That's the reason why locallyClosed is always invoked after remotlyClosed. That doesn't make a difference in the code. When a remote connection is closed, two things could happens: (1) I/O operations return -1 (read/write) (2) I/O operations throws IOException (Win32) in both case the remotlyClosed() will be called. If you have more questions, We should continue that in the mailing list : like that everyone will benefits of the conversation.

How is this feature implemented? Do you report a local connection close event when someone requests the socket to close, and report a remote connection close event when you get an exception during a read?