在这篇文章,我实现一个最简单的协议-DISCARD协议。它把收到的请求数据立即抛弃,而且不做任何回复。
我们知道,Netty是一个事件驱动的网络程序框架,因此我们先从编写我们自己的事件处理器开始。
编写事件处理器
package netty.example.discard;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
// (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// (2)
// Discard the received data silently.
((ByteBuf)msg).release(); // (3)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}