users@grizzly.java.net

Re: [ANN] Getting notified when client or server close the connection.

From: Survivant 00 <survivant00_at_gmail.com>
Date: Wed, 26 Nov 2008 15:16:06 -0500

can I be notify on the client side too ?

I try, but I'm never notify on the client side. I need that for this reason
:

I,m sending requests to the server, and sometime the server will close my
connection and it's will be fine, but in my client I would like to be notify
because it will mean something in the flow of requests that I'll send.

here the code that I have for my client

public class TCPClientTest {

    private static final Logger s_logger =
LoggerFactory.getLogger(TCPClientTest.class);

    private String host = "localhost";
    private int port = 7803;

    private TCPConnectorHandler connector_handler;
    private Controller controller;
    private TCPSelectorHandler tcp_selector_handler;

    private ByteBuffer buf = ByteBufferFactory.allocateView(1000, false);
    private ByteBuffer response = ByteBufferFactory.allocateView(1000,
false);

    public void init() {
        final CountDownLatch started = new CountDownLatch(1);

        controller = new Controller();
        tcp_selector_handler = new TCPSelectorHandler(true);
        controller.addSelectorHandler(tcp_selector_handler);

        controller.addStateListener(new ControllerStateListenerAdapter() {

            public void onException(Throwable e) {
                System.out.println("Grizzly controller exception:" +
e.getMessage());
            }

            public void onReady() {
                System.out.println("Ready!");
                started.countDown();
            }

        });

        BaseSelectionKeyHandler selectionKeyHandler = new
BaseSelectionKeyHandler();

        // to be notify when a client close the connection
        selectionKeyHandler.setConnectionCloseHandler(new
ConnectionCloseHandler() {

            public void locallyClosed(SelectionKey key) {
                   s_logger.debug(key + " is being locally cancelled");
               }

               public void remotlyClosed(SelectionKey key) {
                   s_logger.debug(key + " is being remotly cancelled
(connection closed)");
               }
        });

        tcp_selector_handler.setSelectionKeyHandler(selectionKeyHandler);

        new Thread(controller).start();
        try {
            started.await();
        } catch (Exception e) {
            System.out.println("Timeout in wait" + e.getMessage());
        }

        connector_handler = (TCPConnectorHandler)
controller.acquireConnectorHandler(Controller.Protocol.TCP);
    }

    public void connect(){
        try {
            connector_handler.connect(new InetSocketAddress(host, port), new
CallbackHandler<Context>() {
                public void onConnect(IOEvent<Context> e) {
                    SelectionKey k = e.attachment().getSelectionKey();
                    System.out.println("Callbackhandler: OnConnect...");
                    try {
                        connector_handler.finishConnect(k);
                    } catch (Exception ex) {
                        System.out.println("exception in CallbackHandler:" +
ex.getMessage());
                    }
                    e.attachment().getSelectorHandler().register(k,
SelectionKey.OP_READ);
                }

                public void onRead(IOEvent<Context> ioEvent) {
                    SelectionKey key =
ioEvent.attachment().getSelectionKey();
                    SelectorHandler selectorHandler =
ioEvent.attachment().getSelectorHandler();
                    SocketChannel socketChannel =
(SocketChannel)key.channel();

                    try {
                        if(key.isValid() && key.isReadable()){
                            int count = socketChannel.read(response);
                            if(count>0){
                                response.flip();

                                byte[] b = new byte[(int)count];
                                response.get(b);

                                response.clear();

                                System.out.println(new String(b));
                            }

                            selectorHandler.register(key,
SelectionKey.OP_READ);
                        }
                    } catch (IOException ex){
                        ex.printStackTrace();

selectorHandler.getSelectionKeyHandler().cancel(key);
                    }

                }

                public void onWrite(IOEvent<Context> e) {
                    System.out.println("onWrite");
                }

            });

        } catch (Exception e) {
            System.out.println("Exception in execute..." + e);
            e.printStackTrace(System.out);
        }
    }

    public void send(String quote) throws Exception {
        byte[] msg = quote.getBytes();

        buf = ByteBufferFactory.allocateView(msg.length, false);

        buf.put(msg);
        buf.flip();
        connector_handler.write(buf, true);
        buf.clear();

    }

    public void close(){
        try {
            if(connector_handler!=null){
                connector_handler.close();
            }
            if(controller!=null){
                controller.stop();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TCPClientTest client = new TCPClientTest();

        try {
            client.init();
            client.connect();

            client.send("query");


            Thread.sleep(5000);

            client.close();

            Thread.sleep(300);
        } catch(Exception e){
            e.printStackTrace();
        } finally {
            try {client.close();}catch(Exception e){}
        }

    }

}