关于《Netty权威指南》第三章中TimeServerHandler无法编译通过的解决方法

由于该书出版较早,当前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();
	}
}

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值