第一个netty4的例子

这个例子参与http://netty.io/wiki/user-guide-for-4.x.html文档实现,主要是服务器接收并打印命令行输入的字符,例子简单直接上代码:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.ReferenceCountUtil;

public class DemoServer1 {

	public static void main(String[] args) throws InterruptedException {
		ServerBootstrap bootstrap = new ServerBootstrap();
		EventLoopGroup bossGroup = new NioEventLoopGroup(1); // (1)
	    EventLoopGroup workerGroup = new NioEventLoopGroup(1);
	    try{
	    	bootstrap.group(bossGroup, workerGroup);
		    bootstrap.channel(NioServerSocketChannel.class);
		   
		    bootstrap.childHandler(new ChannelInitializer<SocketChannel>(){

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new MyHandler());
				}
		    	
		    });
		    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
		    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		    ChannelFuture cfuture = bootstrap.bind(8080).sync();
		   cfuture.channel().closeFuture().sync();

	    }finally{
	    	workerGroup.shutdownGracefully();
	    	bossGroup.shutdownGracefully();
	    }
    
	}

}

class MyHandler extends ChannelInboundHandlerAdapter  {
	private int index = 1;

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
		cause.printStackTrace();
		ctx.close();
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		//super.channelRead(ctx, msg);

		  try {
			  System.out.println(((ByteBuf)msg).readableBytes());
			 // System.out.println(((ByteBuf)msg).toString());
			 System.out.println( ((ByteBuf)msg).toString(io.netty.util.CharsetUtil.US_ASCII));
			 System.out.println( ((ByteBuf)msg).toString(io.netty.util.CharsetUtil.US_ASCII));

			  //ctx.write(msg);
			  //ctx.flush();
			 
		    } finally {
		        ReferenceCountUtil.release(msg);
		    }
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}
}

     服务启动后,直接使用telnet就可以和服务进行通信。 

    后边的章节写一下Netty4怎么实现整个NIO通信过程。

猜你喜欢

转载自bzhjian.iteye.com/blog/1971719