一起學Netty(三)之 SimpleChannelInboundHandler
阿新 • • 發佈:2019-01-02
其實Netty的知識點還是很零碎的,比如這個SimpleChannelInboundHandler這個類,在《Netty in Action》該書中的原版的Hello world的demo的客戶端就是使用的SimpleChannelInboundHandler來作為處理器的,我本來也是使用這個類作為我處理類的,但是做一個新手,這個類還是讓我走了一點彎路,我們可以看到SimpleChannelInboundHandler中有一個channelRead0的方法需要我們實現:
尼瑪,我記得當時就是使用的channelRead0這個方法,結果伺服器端就是不列印,伺服器返回的結果,當時客戶端是這樣寫的
- package com.lyncc.netty.component.simplehandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- publicclass BaseClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
- @Override
-
protected
- System.out.println("Client channelRead0 received:" + msg);
- }
- // @Override
- // public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-
// System.out.println("Client channelRead received:" + msg);
- //
- // }
- @Override
- publicvoid exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
- }
- @Override
- publicvoid channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- boolean release = true;
- try {
- if (acceptInboundMessage(msg)) {
- @SuppressWarnings("unchecked")
- I imsg = (I) msg;
- channelRead0(ctx, imsg);
- } else {
- release = false;
- ctx.fireChannelRead(msg);
- }
- } finally {
- if (autoRelease && release) {
- ReferenceCountUtil.release(msg);
- }
- }
- }
- package com.lyncc.netty.component.simplehandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- publicclass BaseClientHandler extends SimpleChannelInboundHandler<String>{
- @Override
- protectedvoid channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
- System.out.println("Client channelRead0 received:" + msg);
- }
- // @Override
- // public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- // System.out.println("Client channelRead received:" + msg);
- //
- // }
- @Override
- publicvoid exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- cause.printStackTrace();
- ctx.close();
- }
- }
SimpleChannelInboundHandler的channelRead0還有一個好處就是你不用關心釋放資源,因為原始碼中已經幫你釋放了,所以如果你儲存獲取的資訊的引用,是無效的~
這個是學習Netty走的一段彎路,在這裡跟大家share一下~