0
点赞
收藏
分享

微信扫一扫

Netty: 解码器要与ChannelHandler配合使用

浮游图灵 2022-07-27 阅读 61


解决粘包问题时,
public class ChildChannelHandler extends ChannelInitializer{

@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
//ch.pipeline().addLast(new MyHandler01());
ch.pipeline().addLast(new MyHandler02());


}

}
添加了2个解码器,Handler里就要相应调整

public class MyHandler02 extends ChannelInboundHandlerAdapter{

@Override
public void channelRead(ChannelHandlerContext ctx,Object msg) throws UnsupportedEncodingException
{

String ttt=(String)msg;
System.out.println(new Date()+" read2 ..."+ttt);




/*
ByteBuf msg0=(ByteBuf)msg;
byte[] bytes=new byte[msg0.readableBytes()];
msg0.readBytes(bytes);
String str=new String(bytes,"UTF-8");
System.out.println(new Date()+" read2 ..."+str);
*/

}

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("connection came2...");

ByteBuf bb=Unpooled.copiedBuffer("this is time from netty2..."+new Date(),CharsetUtil.UTF_8);
ctx.writeAndFlush(bb);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("error occured...");
System.out.println(cause.getMessage());
ctx.close();
}

}


举报

相关推荐

0 条评论