netty java.lang.UnsupportedOperationException: 不支持的消息类型:< type> (预期:...)

使用netty 客户端向netty服务端发送byte[]字节数据,遇到 null java.lang.UnsupportedOperationException: unsupported message type: [B (expected: ByteBuf, FileRegion)
demo:
pom

    <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
     <dependency>
         <groupId>io.netty</groupId>
         <artifactId>netty-all</artifactId>
         <version>4.1.43.Final</version>
     </dependency>
     <!-- https://mvnrepository.com/artifact/io.netty/netty-codec -->
     <dependency>
         <groupId>io.netty</groupId>
         <artifactId>netty-codec</artifactId>
         <version>4.1.43.Final</version>
     </dependency>

client demo:

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap clientBootstrap = new Bootstrap();

            clientBootstrap.group(group);
            clientBootstrap.channel(NioSocketChannel.class);
            clientBootstrap.remoteAddress(new InetSocketAddress("localhost", 2049));
            clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ClientHandler());
                }
            });
            ChannelFuture channelFuture = clientBootstrap.connect().sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            System.err.println(e.getCause() + "\t\t" + e.getMessage());
        } finally {
            group.shutdownGracefully().sync();
        }
    }

自定义ClientHandler

import com.jiang.vo.ResultVo;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.TimeUnit;

public class ClientHandler extends SimpleChannelInboundHandler<byte[]> {

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) {
        System.err.println("==================即将要向服务端写入数据=================");
        byte[] bytes = getBytes();
        System.err.println("==================即将要向服务端写入数据=================" + bytes.length);
        channelHandlerContext.writeAndFlush(bytes).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                StringBuilder sb = new StringBuilder("");
                if (future.isSuccess()) {
                    System.err.println(sb.toString() + "回写成功.");
                } else {
                    System.err.println(sb.toString() + "回写失败.");
                    System.err.println("\t\t链接失败原因\t" + future.cause().getCause() + "\t" + future.cause().toString());
                    future.channel().eventLoop().schedule(new Runnable() {
                        @Override
                        public void run() {

                        }
                    }, 10, TimeUnit.SECONDS);
                }
            }
        });
    }

    private byte[] getBytes() {
        System.err.println("=============参数设置=======================");
        ResultVo resultVo = new ResultVo(2, "fdsafdsafdsafd".getBytes());
        byte[] finalResult = resultVo.getFinalResult();
        ResultVo vo = new ResultVo(1, finalResult);
        return vo.getFinalResult();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) {
        cause.printStackTrace();
        channelHandlerContext.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, byte[] bytes) throws Exception {
        System.out.println("Client received: " + new String(bytes));
    }
}

在这里插入图片描述
默认的Netty频道只能发送 ByteBuf s和 FileRegion s。您需要通过向管道添加更多处理程序或将其手动转换为 ByteBuf s将对象转换为这些类型。
A ByteBuf 是字节数组的Netty变体,但具有性能潜力,因为它可以存储在直接存储空间中。
转换 String < / code>使用 StringEncoder
转换 Serializable 使用 ObjectEncoder (警告,与普通Java对象流不兼容)
转换 byte [] 使用 ByteArrayEncoder
当客户端和服务都需要使用字节流的时候,需要如下设置

ChannelPipeline pipeline = ...;
/ / 解码
/ / Decoders
pipeline.addLast(new ByteArrayDecoder());
/ / 编码
// Encoder
pipeline.addLast(new ByteArrayEncoder());
/ / 然后您可以使用字节数组而不是ByteBuf作为一个信息:
void channelRead(ChannelHandlerContext ctx, byte[] bytes) {
...
}

将上面代码做如下修改,就成功传送字节数组到服务端

    clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new ByteArrayEncoder());
                    socketChannel.pipeline().addLast(new ClientHandler());
                }
            });
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值