Netty权威指南(笔记二)

第三章 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();
    }
}



















你可能感兴趣的:(Netty)