package com.netty.examples.discard;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
@Sharable
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
System.out.println("Server received: " + msg);
ctx.write(msg);
ctx.flush();
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
@Sharable annotation 表明Handler可以在不同Channel之间共享。
ctx.writeAndFlush()方法 "flush" the messages to the remote peer yet.
DiscardServerHandler继承自ChannelInboundHandlerAdapter,你必须显示调用方法
ReferenceCountUtil.release(msg)释放资源。