users@grizzly.java.net

Re: unable to create a grizzly client using ProtocolChain

From: Survivant 00 <survivant00_at_gmail.com>
Date: Tue, 23 Dec 2008 09:00:04 -0500

I'm usiong Grizzly 1.9.2

here the same program but with a callbackHandler. (ok.. I have more stuff
like a stateListener... but that won't change that I received messages)

package grizzly.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.grizzly.BaseSelectionKeyHandler;
import com.sun.grizzly.CallbackHandler;
import com.sun.grizzly.Context;
import com.sun.grizzly.Controller;
import com.sun.grizzly.ControllerStateListenerAdapter;
import com.sun.grizzly.IOEvent;
import com.sun.grizzly.SelectorHandler;
import com.sun.grizzly.TCPConnectorHandler;
import com.sun.grizzly.TCPSelectorHandler;
import com.sun.grizzly.util.ByteBufferFactory;
import com.sun.grizzly.util.ConnectionCloseHandler;

public class TCPClient {

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

    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) {
                s_logger.error("Grizzly controller exception:" +
e.getMessage());
            }

            public void onReady() {
                if(s_logger.isDebugEnabled()){
                    s_logger.debug("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) {
                    if(s_logger.isDebugEnabled()){
                        s_logger.debug(key + " is being locally cancelled");
                    }
               }

               public void remotlyClosed(SelectionKey key) {
                   if(s_logger.isDebugEnabled()){
                       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) {
            s_logger.error("Timeout in wait" + e.getMessage());
        }

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

    public void connect(String host, int port){
        try {
            connector_handler.connect(new InetSocketAddress(host, port), new
CallbackHandler<Context>() {
                public void onConnect(IOEvent<Context> e) {
                    SelectionKey k = e.attachment().getSelectionKey();
                    if(s_logger.isDebugEnabled()){
                        s_logger.debug("Callbackhandler: OnConnect...");
                    }
                    try {
                        connector_handler.finishConnect(k);
                    } catch (Exception ex) {
                        s_logger.error("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();
                                if(s_logger.isDebugEnabled()){
                                    s_logger.debug(new String(b));
                                }
                            }

                            selectorHandler.register(key,
SelectionKey.OP_READ);
                        }
                    } catch (IOException ex){
                        if(s_logger.isDebugEnabled()){
                            s_logger.debug("IOException", ex);
                        }

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

                }

                public void onWrite(IOEvent<Context> e) {
                    if(s_logger.isDebugEnabled()){
                        s_logger.debug("onWrite");
                    }
                }

            });

        } catch (Exception e) {
            s_logger.error("Exception in execute..." + e);
        }
    }

    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) {
            s_logger.error("IOException", e);
        }
    }

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

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

        try {
            client.init();
            client.connect(host, port);

            client.send("hello[eoq]");

            Thread.sleep(5000);

            client.close();

            Thread.sleep(300);
        } catch(Exception e){
            s_logger.error("main", e);
        } finally {
            try {client.close();}catch(Exception e){}
        }

    }
}