博客
关于我
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/

你可能感兴趣的文章
python读取含中文的json
查看>>
python | 如何用Python锁避免并发错误?
查看>>
python | 提升代码迭代速度的Python重载方法
查看>>
python | 深入理解Python并发编程中的GIL限制与解决方案
查看>>
Python | 爬虫实战——亚马逊搜索页监控(附详细源码)
查看>>
python | 高效使用Python工具自动生成模块文档的秘诀
查看>>
python 一个list去除另一个list中的值
查看>>
python 三大框架的 介绍。
查看>>
Python 下载的 11 种姿势,一种比一种高级!
查看>>
python读取一个文件夹下所有图片_初学Python-找出文件夹下的所有图片
查看>>
Python 中 3 个不可思议的返回功能
查看>>
python 中 dict 的另一种用法
查看>>
Python 中 PIL 读取图片出现异常旋转的解决方法
查看>>
python读取word表格内容(1)
查看>>
python 中os.path.join 双斜杠的解决办法
查看>>
python 中PIL.Image和OpenCV图像格式相互转换
查看>>
Python 中Semaphore 信号量对象、Event事件、Condition
查看>>
python 中with的使用及样例
查看>>
python读取wav文件并播放[pyaudio/wave]
查看>>
python读取txt文件的行数
查看>>