博客
关于我
Netty传输
阅读量:559 次
发布时间:2019-03-09

本文共 3664 字,大约阅读时间需要 12 分钟。

Netty传输API的核心是Channel接口,它用于实现所有的I/O操作

每个Channel都会分配一个ChannelPipeline和ChannelConfig。ChannelConfig包含该Channel的所有配置设置,且支持热更新。由于特定的传输可能需要独特的配置设置,因此它可能会实现ChannelConfig的子接口。

Channel是独一无二的,因此为了保证排序,Channel声明为Comparable接口的子接口。如果两个不同的Channel实例返回相同的散列码,AbstractChannel的compareTo()方法将抛出错误。

ChannelPipeline实现了拦截过滤器模式,持有所有处理入站和出站数据及事件的ChannelHandler。ChannelHandler用于处理状态变化、数据处理以及用户定义事件等。

ChannelHandler的典型功能包括:

  • 数据格式转换
  • 异常通知
  • Channel状态变化通知
  • 注册到EventLoop/注销通知
  • 用户定义事件通知

Channel的核心方法

  • eventLoop:返回分配给Channel的EventLoop
  • pipeline:返回分配给Channel的ChannelPipeline
  • isActive:如果Channel处于活动状态,返回true
  • localAddress、remoteAddress:返回本地和远程的SocketAddress
  • write:将数据写入远端节点
  • flush:将缓冲的数据冲刷到底层传输(如socket)
  • writeAndFlush:简便方法,等同于write()和flush()

内置传输类型

  • NIO(java.nio.channels包):基于选择器的非阻塞I/O
  • Epoll:JNI驱动的epoll,适用于Linux
  • OIO:基于java.net包的阻塞I/O
  • Local:JVM内部通信(不涉及网络流量)
  • Embedded:嵌入式传输,用于ChannelHandler测试

注意事项

  • 零拷贝仅适用于NIO和Epoll传输,用于文件到网络接口快速传输
  • Local传输不支持实体网络流量,客户端需使用同一传输类型-_based传输在同一JVM内通信的完美用例
  • 测试ChannelHandler时使用Embedded传输

应用场景

  • 非阻塞代码库:建议使用NIO或Epoll
  • 阻塞代码库:建议使用OIO
  • JVM内部通信:使用Local传输
  • ChannelHandler测试:使用Embedded传输

示例代码

// 服务器端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/

你可能感兴趣的文章
QT样式表——url路径
查看>>
QT数据库(三):QSqlQuery使用
查看>>
QT教程5:消息框
查看>>
SpringBoot中集成阿里开源缓存访问框架JetCache实现声明式实例和方法缓存
查看>>
pom.xml中提示web.xml is missing and <failonmissingw>...
查看>>
Pomelo开发中Web客户端开发API简介
查看>>
QT教程2:QT5的体系构架
查看>>
PON架构(全光网络)
查看>>
PoolingHttpClientConnectionManager原理剖析
查看>>
QT教程1:ubuntu18.04安装QT5
查看>>
POP-一个点击带有放大还原的动画效果
查看>>
POP3 协议在计算机网络中的优缺点
查看>>
qt批量操作同类型控件
查看>>
Portaudio笔记-WASAPI
查看>>
position:fixed失效情况
查看>>
Qt开发笔记:QGLWidget、QOpenGLWidget详解及区别
查看>>
Position属性四个值:static、fixed、absolute和relative的区别和用法
查看>>
POSIX thread编程中关于临界区内条件变量的分析
查看>>
POSIX与程序可移植性
查看>>
posix多线程有感--自旋锁
查看>>