'How to handle udp byte array with netty?
I used netty to accept the byte array transmitted by UDP protocol.However, once the array exceeds 8 bits, an error will occur.example,when I send byte array [c 1 2 0 0 0 5 12 34 ff 0 59],netty will receive [12, 1, 2, 0, 0, 0, 5, 18, 3, 3, 15, 0 89]. Server`s code:
@Component
public class TestUdp implements ApplicationRunner {
private void start(){
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(bossGroup)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST,true)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
nioDatagramChannel.pipeline().addLast(new MyUdpDecoder());
}
});
ChannelFuture future = bootstrap.bind(9510).sync();
future.channel().closeFuture().await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
}
}
@Override
public void run(ApplicationArguments args) throws Exception {
start();
}
decoder`s code:
@Slf4j
public class MyUdpDecoder extends MessageToMessageDecoder<DatagramPacket> {
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> list) throws Exception {
ByteBuf buf = packet.content();
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
int[] reqInt = getResult(bytes);
log.info("data:"+ Arrays.toString(reqInt));
}
public static int[] getResult(byte[] obj){
int first = 0xff & obj[0];
obj = Arrays.copyOf(obj, first);
int[] result = new int[obj.length];
result[0] = first;
for (int i = 1; i < obj.length; i++) {
result[i] = 0xff & obj[i];
}
return result;
}
}
you can copy the code and run in any springboot project.Thank you very much for your help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
