netty writeAndFlush不起作用

请看下面的发送writeAndFlush

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

		ByteBuf bb = (ByteBuf) msg;
		ctx.writeAndFlush(bb);
		ctx.writeAndFlush("end");
		ctx.writeAndFlush(new byte[] {
    
    1,2,3});
		
	}

发现他能返回ByteBuf 的,但是却无法返回字符串和byte数组
这是为什么?
因为netty默认是讲byte数组解码编码成ByteBuf
如果想传输不同类型的数据,需要在netty启动类里添加编码器.

			.childHandler(new ChannelInitializer<Channel>() {
    
    
				@Override
				protected void initChannel(Channel ch) throws Exception {
    
    
					ch.pipeline()
					.addLast(new StringEncoder())//添加字符串编码器
					.addLast(new ByteArrayEncoder())//添加字节数组的编码器
					.addLast(new MyNioServerHandler())
					;
						
				}
			});

这样符合相应的类型就可以编码传输了.
值得注意的是:这里只是添加了encoder编码器,是发送时候需要的.如果接受时需要解码也需要相应的解码器.
其次,StringEncoder和ByteArrayEncoder在同一个包下,是netty自带的解码编码器.里面也有其他类型的.

猜你喜欢

转载自blog.csdn.net/dmw412724/article/details/113181172