使用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());
}
});