本文共 3664 字,大约阅读时间需要 12 分钟。
Netty传输API的核心是Channel接口,它用于实现所有的I/O操作
每个Channel都会分配一个ChannelPipeline和ChannelConfig。ChannelConfig包含该Channel的所有配置设置,且支持热更新。由于特定的传输可能需要独特的配置设置,因此它可能会实现ChannelConfig的子接口。
Channel是独一无二的,因此为了保证排序,Channel声明为Comparable接口的子接口。如果两个不同的Channel实例返回相同的散列码,AbstractChannel的compareTo()方法将抛出错误。
ChannelPipeline实现了拦截过滤器模式,持有所有处理入站和出站数据及事件的ChannelHandler。ChannelHandler用于处理状态变化、数据处理以及用户定义事件等。
ChannelHandler的典型功能包括:
Channel的核心方法
内置传输类型
注意事项
应用场景
示例代码
// 服务器端public class EchoServer { private final ByteBuf buffer = Unpooled.copiedBuffer("Hello, Yang", Charset.UTF_8); public void bind(int port) throws Exception { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); try { bootstrap.group(boss, worker).channel(NioServerSocketChannel.class) .childHandler(new ChildChannelHandler()); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String message = buf.toString(Charset.UTF_8); System.out.println("_received: " + message); ctx.writeAndFlush(buf); } }); } }} // 客户端
public class EchoClient { private final ByteBuf buffer = Unpooled.copiedBuffer("Hello, Wang", Charset.UTF_8); public void connect(int port, String host) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChildChannelHandler()); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer { @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String message = buf.toString(Charset.UTF_8); System.out.println("_received: " + message); ctx.close(); } }); } }} 参考《Netty实战》
转载地址:http://ghmsz.baihongyu.com/