实现一个无响应的server
Talk is cheap. Show me the code.
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
try {
System.out.println((char) in.readByte());
} finally {
in.release();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
- 这里DiscardServerHandle继承了ChannelInboundHandlerAdapter,ChannelInboundHandlerAdapter又实现了ChannelInboundHandler接口。ChannelInboundHandler接口提供了各种各样的事件处理方法(即事件发生时的回调方法)以供重写。这里我们继承ChannelInboundHandlerAdapter就够了不用去实现ChannelInboundHandler接口。
- 我们重写了channelRead方法,这个方法就是在接收到来自客户端的数据时被调用。例子中的数据就是ByteBuf类型的。
- ByteBuf是一个计数引用的对象,它需要明确地调用release()才能被释放。切记,自定义handler中释放计数引用对象是很有必要的。
- exceptionCaught()是在netty发生I/O错误或者handler实现处理其他事件时发生的错误抛出异常时才会被调用。在大多数情况下,发生的异常都应该被记录,并且与之关联的channel也应该被关闭。