第一个netty4的例子_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 第一个netty4的例子

第一个netty4的例子

 2013/11/5 18:36:43  bzhjian  程序员俱乐部  我要评论(0)
  • 摘要:这个例子参与http://netty.io/wiki/user-guide-for-4.x.html文档实现,主要是服务器接收并打印命令行输入的字符,例子简单直接上代码:importio.netty.bootstrap.ServerBootstrap;importio.netty.buffer.ByteBuf;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelHandlerContext;importio
  • 标签:net 例子 一个

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

class="java" name="code">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通信过程。

?

发表评论
用户名: 匿名