netty SimpleChannelInboundHandler类继承使用
2019獨角獸企業重金招聘Python工程師標準>>>
繼承一個SimpleChannelInboundHandler來實現我們的Client,我們需要重寫其中的三個方法:
package?NettyDemo.echo.handler;import?io.netty.buffer.ByteBuf; import?io.netty.buffer.ByteBufUtil; import?io.netty.buffer.Unpooled; import?io.netty.channel.ChannelHandlerContext; import?io.netty.channel.SimpleChannelInboundHandler; import?io.netty.channel.ChannelHandler.Sharable; import?io.netty.util.CharsetUtil; @Sharable public?class?EchoClientHandler?extends?SimpleChannelInboundHandler<ByteBuf>?{??/**???*此方法會在連接到服務器后被調用?*?*/??public?void?channelActive(ChannelHandlerContext?ctx)?{????ctx.write(Unpooled.copiedBuffer("Netty?rocks!",?CharsetUtil.UTF_8));??}??/**???*此方法會在接收到服務器數據后調用?*?*/??public?void?channelRead0(ChannelHandlerContext?ctx,?ByteBuf?in)?{????System.out.println("Client?received:?"?+?ByteBufUtil.hexDump(in.readBytes(in.readableBytes())));??}/**???*捕捉到異常?*?*/??public?void?exceptionCaught(ChannelHandlerContext?ctx,?Throwable?cause)?{????cause.printStackTrace();????ctx.close();??}}? ? 其中需要注意的是?channelRead0()方法,此方法接收到的可能是一些數據片段,比如服務器發送了5個字節數據,Client端不能保證一次全部收到,比如第一次收到3個字節,第二次收到2個字節。我們可能還會關心收到這些片段的順序是否可發送順序一致,這要看具體是什么協議,比如基于TCP協議的字節流是能保證順序的。
? ? 還有一點,在Client端我們的業務Handler繼承的是SimpleChannelInboundHandler,而在服務器端繼承的是ChannelInboundHandlerAdapter,那么這兩個有什么區別呢?最主要的區別就是SimpleChannelInboundHandler在接收到數據后會自動release掉數據占用的Bytebuffer資源(自動調用Bytebuffer.release())。而為何服務器端不能用呢,因為我們想讓服務器把客戶端請求的數據發送回去,而服務器端有可能在channelRead方法返回前還沒有寫完數據,因此不能讓它自動release。
轉載于:https://my.oschina.net/u/1013711/blog/383006
總結
以上是生活随笔為你收集整理的netty SimpleChannelInboundHandler类继承使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bzoj 3289: Mato的文件管理
- 下一篇: 安卓获取星期几