如题。我需要向一个RFID标签发送一段请求帧,然后标签会返还一个响应帧,通过返回的响应帧来获取数据。但是RFID仅支持原生的二进制数据传输,而netty是需要用ByteBuf进行封装的。
请问netty有办法支持这样的数据传输吗。传输的方式是TCP/IP
我自己已经解决了,这是两个测试的类,有需要的可以参考一下:
public class AgvTcpServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(3001);
Socket socket = serverSocket.accept();
try {
TimeUnit.SECONDS.sleep(2);
while (true){
socket.setKeepAlive(true);
final InputStream is = socket.getInputStream();
final byte[] bytes = new byte[16];
is.read(bytes);
System.out.println("==================");
for (byte aByte : bytes) {
System.out.print(aByte + " ");
}
System.out.println("
=================");
final OutputStream os = socket.getOutputStream();
os.write(bytes);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
socket.close();
serverSocket.close();
}
}
}
客户端
@Slf4j
public class AgvClient {
public static void main(String[] args) throws InterruptedException {
final NioEventLoopGroup group = new NioEventLoopGroup();
final Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
//限制接受帧的长度
pipeline.addLast(new FixedLengthFrameDecoder(16));
pipeline.addLast(new ByteArrayDecoder());
pipeline.addLast(new ByteArrayEncoder());
pipeline.addLast(new AgvClientHandler3());
}
});
log.info("Client initialized successfully");
final ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 3001).sync();
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
客户端Handler
@Slf4j
public class AgvClientHandler3 extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
final byte[] bytes = new byte[16];
bytes[0] = (byte) 0xaa;
bytes[1] = (byte) 0x01;
bytes[2] = (byte) 0x01;
bytes[14] = (byte) 0xff;
bytes[15] = (byte) 0xab;
ctx.writeAndFlush(bytes);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
final byte[] bytes = (byte[]) msg;
bytes[3] = 0x00;
log.info(Arrays.toString(bytes));
ctx.writeAndFlush(bytes);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}