Netty发送消息无法接收问题
原因:
参考官网案例代码,继承ChannelHandlerAdapter类,则writeAndFlush只接受ByteBuf对象,因此需要将需要发送的数据转换成ByteBuf
其他
- 字符串转ByteBuf
String str = "haha";
ByteBuf byteBuf = Unpooled.wrappedBuffer(str.getBytes());
- 数字转ByteBuf
int number = 123456;
// 创建一个具有足够容量的ByteBuf
ByteBuf byteBuf = Unpooled.buffer(Integer.BYTES); // 这里假设我们要处理的是一个32位整数,如果要处理其他大小的整数,需要调整创建ByteBuf的容量,并相应地使用writeShort、writeLong等方法
// 写入整数到ByteBuf
byteBuf.writeInt(number);
- 对象转ByteBuf
//对象要求实现Serializable接口
Date object = new Date();
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
byte[] bytes = bos.toByteArray();
ByteBuf byteBuf = Unpooled.buffer(bytes.length);
byteBuf.writeBytes(bytes);
} catch (IOException e) {
e.printStackTrace();
}
- 布尔转ByteBuf
boolean bool = true;
ByteBuf byteBuf = Unpooled.buffer(1);
byteBuf.writeByte(bool ? (byte) 1 : (byte) 0);
标签:Netty,ByteBuf,buffer,bytes,Unpooled,发送,byteBuf,接收
From: https://www.cnblogs.com/nicolasfive/p/18183604