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();
            tcpSelectorHandler.setPort(port);
        
            Pipeline pipeline = new DefaultPipeline();
            pipeline.setMaxThreads(5);
            
            controller.setPipeline(pipeline);
            
            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)");
                   }
            });
            
            tcpSelectorHandler.setSelectionKeyHandler(selectionKeyHandler);
            
            controller.addSelectorHandler(tcpSelectorHandler);
            
            ..... add here your protocolChain
            
      try {
         controller.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        } catch (Exception e) {
            System.out.println("exit");
        }
}

Related Topics >>

Comments

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 : users@grizzly.dev.java.net 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?