由于该书出版较早,当前Netty已经升级到了4.1.37,Netty对架构进行了较大的改进工作,因此书中的部分例子无法正常编译通过。该书第三章中TimeServer需要用到TimeServerHandler类,该类继承自ChannelHandlerAdapter,覆盖了channelRead、channelReadComplete两个父类方法。但在当前版本的Netty中,ChannelHandlerAdapter已不存在这两个方法,初学者往往不知所措。在当前版本的Netty中,对ChannelHandler进行了细化,派生出ChannelInboundHandler和ChannelOutboundHandler两个接口,将读写功能分开,前面提到的两个方法也自然而然的移到了ChannelInboundHandler中,因此对TimeServerHandler做如下修改即可成功编译执行:
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception{
ByteBuf buf = (ByteBuf) msg;
byte[] req=new byte[buf.readableBytes()];
buf.readBytes(req);
String body=new String(req,"UTF-8");
System.out.println("The time server receive order : "+body);
String currentTime="QUERY TIME ORDER".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString():"BAD ORDER";
ByteBuf resp=Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception{
ctx.close();
}
}