Netty権威ガイド(メモ2)

4495 ワード

第三章Netty入門
3.1必要なjarパッケージ
netty-all-5.0.0をインポートする.Alpha1.jarのパッケージ.
3.2サービス側コード
public class TimeServer {

	public void bind(int port) throws Exception{
		//NioEventLoopGroup 
		EventLoopGroup bossGroup = new NioEventLoopGroup();// 
		EventLoopGroup workerGroup = new NioEventLoopGroup();// SocketChannel 
		try {
			//ServerBootstrap NIO 
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)	// NIO ServerBootstrap 
			.channel(NioServerSocketChannel.class)	// Channel NioServerSocketChannel
			.option(ChannelOption.SO_BACKLOG, 1024)	// TCP backlog 1024
			.childHandler(new ChildChannelHander());	// ChildChannelHander
			
			// , 
			ChannelFuture f = b.bind(port).sync();
			
			// 
			f.channel().closeFuture().sync();
		} finally{
			// , 
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}	
	}
	
	private class ChildChannelHander extends ChannelInitializer{

		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new TimeServerHandler());
		}	
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if(args!=null && args.length>0){
			try{
				port = Integer.valueOf(args[0]);
			}catch(NumberFormatException e){
				
			}
		}
		new TimeServer().bind(port);
	}
	
}

TimeServerHandlerクラス
public class TimeServerHandler extends ChannelHandlerAdapter {

	// , channelRead exceptionCaught 
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
	    throws Exception {
	ByteBuf buf = (ByteBuf) msg;
	byte[] req = new byte[buf.readableBytes()];
	buf.readBytes(req);
	String body = new String(req, "UTF-8");
	System.out.println("The time server receive order : " + body);
	String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(
		System.currentTimeMillis()).toString() : "BAD ORDER";
	ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
	ctx.write(resp);// 
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
	ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
	ctx.close();
    }
}

3.3クライアントコード
public class TimeClient {

	public void connect(int port,String host) throws Exception{
		// NIO 
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());
				}
			});
			// 
			ChannelFuture f = b.connect(host, port).sync();
			// 
			f.channel().closeFuture().sync();
		} finally{
			// , NIO 
			group.shutdownGracefully();
		}	
	}
	
	
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if(args!=null && args.length>0){
			try {
			port = Integer.valueOf(args[0]);	
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}
		}
		new TimeClient().connect(port, "127.0.0.1");
	}

}

TimeClientHandlerクラス
public class TimeClientHandler extends ChannelHandlerAdapter {

	
    private static final Logger logger = Logger
	    .getLogger(TimeClientHandler.class.getName());

    private final ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public TimeClientHandler() {
	byte[] req = "QUERY TIME ORDER".getBytes();
	firstMessage = Unpooled.buffer(req.length);
	firstMessage.writeBytes(req);

    }

    // TCP 
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
	ctx.writeAndFlush(firstMessage);
    }

    // 
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
	    throws Exception {
	ByteBuf buf = (ByteBuf) msg;
	byte[] req = new byte[buf.readableBytes()];
	buf.readBytes(req);
	String body = new String(req, "UTF-8");
	System.out.println("Now is : " + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
	//  
	logger.warning("Unexpected exception from downstream : "
		+ cause.getMessage());
	ctx.close();
    }
}