Grizzly學習筆記(二) – JAVA編程語言程序開發技術文章

上一篇的client比較簡單,下面是一個復雜點的:package org.guojje.grizzly; 
 
import java.io.IOException; 
import java.net.InetAddress; 
import java.net.InetSocketAddress; 
import java.net.UnknownHostException; 
import java.nio.ByteBuffer; 
import java.nio.channels.SelectionKey; 
import java.util.concurrent.CountDownLatch; 
import java.util.logging.Level; 
 
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.TCPConnectorHandler; 
import com.sun.grizzly.TCPSelectorHandler; 
import com.sun.grizzly.Controller.Protocol; 
import com.sun.grizzly.util.WorkerThreadImpl; 
 
public class Client { 
 
    public static void main(String[] args) throws UnknownHostException, 
            IOException { 
 
        Controller controller = new Controller(); 
 
        // it is true for client 
        TCPSelectorHandler tcpHandler = new TCPSelectorHandler(true); 
        controller.setSelectorHandler(tcpHandler); 
 
        final CountDownLatch latch = new CountDownLatch(1); 
        controller.addStateListener(new ControllerStateListenerAdapter() { 
 
            public void onStarted() { 
                System.out.println("on started"); 
            } 
 
            public void onReady() { 
                System.out.println("on ready"); 
                latch.countDown(); 
            } 
 
            public void onException(Throwable e) { 
                if (latch.getCount() > 0) { 
                    Controller.logger().log(Level.SEVERE, 
                            "Exception during " + "starting the controller", e); 
                    latch.countDown(); 
                } else { 
                    Controller.logger().log(Level.SEVERE, 
                            "Exception during " + "controller processing", e); 
                } 
            } 
        }); 
        // controller.start(); 這裡不能再用controller.start()來啟動controller 
        // 因為他會阻塞當前線程 
        new WorkerThreadImpl("client_work", controller).start(); 
 
        try { 
            latch.await(); 
        } catch (InterruptedException e1) { 
            // do nothing 
        } 
 
        if (!controller.isStarted()) { 
            throw new IllegalStateException("Controller is not started!"); 
        } 
 
        final CountDownLatch waitLatch = new CountDownLatch(1); 
 
        final TCPConnectorHandler tch = (TCPConnectorHandler) controller 
                .acquireConnectorHandler(Protocol.TCP); 
        tch.connect(new InetSocketAddress(InetAddress.getLocalHost(), 1900), 
                new CallbackHandler<Context>() { 
 
                    public void onConnect(IOEvent<Context> ioEvent) { 
                        try { 
                            SelectionKey k = ioEvent.attachment() 
                                    .getSelectionKey(); 
                            try { 
                                tch.finishConnect(k); 
                                // log("finishConnect"); 
                            } catch (java.io.IOException ex) { 
                                // ioExceptionHandler.handle(ex); 
                                return; 
                            } catch (Throwable ex) { 
                                // logger().log(Level.SEVERE, "onConnect", ex); 
                                return; 
                            } 
                            // 註冊Read事件 
                            ioEvent.attachment().getSelectorHandler().register( 
                                    k, SelectionKey.OP_READ); 
 
                        } finally { 
                            if (waitLatch != null) { 
                                waitLatch.countDown(); 
                            } 
                        } 
                    } 
 
                    public void onRead(IOEvent<Context> ioEvent) { 
                        ByteBuffer bb = ByteBuffer.allocate(100); 
                        try { 
                            tch.read(bb, false); 
                        } catch (IOException e) { 
                            e.printStackTrace(); 
                        } 
                        bb.flip(); 
                        System.out.println(new String(bb.array(), 0, bb 
                                .remaining())); 
 
                        SelectionKey k = ioEvent.attachment().getSelectionKey(); 
                        // 重新註冊read事件,原因參考TcpSelectorHandler的onReadInterest/onWriteInterest方法 
                        ioEvent.attachment().getSelectionKey().interestOps( 
                                k.interestOps() | SelectionKey.OP_READ); 
                    } 
 
                    public void onWrite(IOEvent<Context> ioEvent) { 
                    } 
                }); 
 
        System.out.println("current connection:" + tch.getUnderlyingChannel()); 
 
        try { 
            waitLatch.await(); 
        } catch (Exception e) { 
            // do nothing 
        } 
 
        ByteBuffer bb = ByteBuffer.wrap("xxxx".getBytes()); 
        tch.write(bb, true); 
    } 
}
 
本文出自 “天下無賊” 博客

發佈留言