Grizzly学习笔记(二)(一)

2014-11-24 02:29:11 · 作者: · 浏览: 0

上一篇的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() {

public void onConnect(IOEvent 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) {