Netty异步IO和回调函数
来源:互联网 发布:w7内外网转换软件 编辑:程序博客网 时间:2024/06/06 00:36
Netty异步IO和回调函数
在Netty中,write及writeAndFlush方法有个返回值,类型是ChannelFuture。ChannelFuture的addListener方法可以添加ChannelFutureListener监听器。ChannelFutureListener接口的抽象方法operationComplete会在write完成(无论成功或失败)时被调用,我们只需要实现这个方法即可处理一些write完成后的操作,例如write完成后关闭连接。
public class Server {public void start() throws InterruptedException {EventLoopGroup eventLoopGroup = new NioEventLoopGroup();EventLoopGroup eventLoopGroup2 = new NioEventLoopGroup();ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(eventLoopGroup, eventLoopGroup2).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {@Overrideprotected void initChannel(Channel arg0) throws Exception {ChannelPipeline pipeline = arg0.pipeline();pipeline.addLast(new ServerHandler());}});ChannelFuture future = serverBootstrap.bind(6699).sync();System.out.println("Server.start()");future.channel().closeFuture().sync();}public static void main(String[] args) {Server server = new Server();try {server.start();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf>{@Overrideprotected void channelRead0(ChannelHandlerContext arg0, ByteBuf arg1) throws Exception {}@Overridepublic void channelRead(final ChannelHandlerContext ctx, Object arg1) throws Exception {String string = "to C";ByteBuf buf = Unpooled.buffer(string.length());buf.writeBytes(string.getBytes());ChannelFuture future = ctx.writeAndFlush(buf);future.addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture arg0) throws Exception {if(arg0.isSuccess()) { // 是否成功System.out.println("write操作成功");} else {System.out.println("write操作失败");}ctx.close(); // 如果需要在write后关闭连接,close应该写在operationComplete中。注意close方法的返回值也是ChannelFuture}});}}
阅读全文
0 0
- Netty异步IO和回调函数
- Mina、Netty、Twisted一起学(九):异步IO和回调函数
- MINA、Netty、Twisted一起学(九):异步IO和回调函数
- 异步调用和回调函数
- 异步调用和回调函数
- 回调函数 异步执行
- 异步委托调用和回调函数的结合使用
- 同步调用、异步调用和回调函数
- python异步回调函数的实现
- 同步调用、回调函数、异步调用
- c#异步,(无回调函数)
- ajax异步执行回调函数内容
- JavaScript异步编程 回调函数
- ajax回调函数 异步延迟
- Javascript异步编程方法---“回调函数”
- java 回调函数同步、异步调用
- node.js异步式回调函数
- Ajax异步回调函数(callback)
- Go学习笔记02
- ccs5.5 编译错误
- JAVA并行流导致的 No thread-bound request found
- Linux---RH254---unit 6 NFS
- hdu 5971 Wrestling Match 判断能否构成二分图 [Problem A]2016ACM/ICPC亚洲区大连站
- Netty异步IO和回调函数
- Android---------HttpURLConnection的 get 请求和 post 请求(更容易理解)
- HDU 1532 Drainage Ditches——最大流EK算法
- phpcms v9网站搬家更换域名的方法
- VS调试网站时分析器错误
- 059、060、061-C++
- mac效率工具之moom
- [Leetcode] 198. House Robber 解题报告
- OpenCV学习笔记(23)findContours与drawContours