netty4 ChannelInboundHandler 使用
所属分类 netty
浏览量 1494
入站处理 ChannelInboundHandler
出站处理 ChannelOutboundHandler
ChannelInboundHandler
ChannelInboundHandlerAdapter
SimpleChannelInboundHandler
void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception;
void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception;
channelRead 处理 msg
一般使用 ChannelInboundHandlerAdapter
public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler {
public class HelloInHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof ByteBuf){
ByteBuf in = (ByteBuf)msg;
try {
if(in.readableBytes() > 0){
String str = in.toString(CharsetUtil.UTF_8);
System.out.println("receive msg:" + str);
}
} finally {
// 释放资源 !!!
ReferenceCountUtil.release(in);
}
}
}
}
继承 ChannelInboundHandlerAdapter 注释资源释放
ReferenceCountUtil.release
SimpleChannelInboundHandler 把资源释放逻辑模板化
public abstract class SimpleChannelInboundHandler< I > extends ChannelInboundHandlerAdapter {
@Override
public void 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);
}
}
}
// 需要我们主动实现的接口
protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception;
...
}
public class HelloSimpleInHandler extends SimpleChannelInboundHandler< ByteBuf > {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
if(msg.readableBytes() > 0){
String str = msg.toString(CharsetUtil.UTF_8);
System.out.println("receive msg: " + str);
}
}
}
继承 SimpleChannelInboundHandler ,实现 channelRead0 不需要释放资源
StringDecoder + HelloHandler
public class HelloHandler extends SimpleChannelInboundHandler< String > {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println("receive msg: " + msg);
}
}
bootstrap.childHandler(new ChannelInitializer< Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new HelloHandler());
}
}
使用 LineBasedFrameDecoder 按 换行符解码消息
public class LineBasedFrameDecoder extends ByteToMessageDecoder
A decoder that splits the received ByteBuf s on line endings.Both "\n" and "\r\n" are handled.
For a more general delimiter-based decoder, see DelimiterBasedFrameDecoder
上一篇
下一篇
netty实战笔记
netty中的future和promise
netty耗时任务处理
ChannelPipeline和ChannelInitializer
netty ByteBuf 使用
dubbo实例