我有一个应用程序,通过TCp发送sendind LogRecord,我想捕获这些日志。我是Netty的新手,在用一些例子进行捕获后,我无法读取LogRecord对象。
我尝试获取字节数组来反序列化对象,但是我收到了错误。有人可以给我一个很好的例子或提示。
以下是代码:
@Component
@Qualifier("socketChannelInitializer")
public class SocketChannelInitializer extends ChannelInitializer<SocketChannel> {
private static final ByteArrayDecoder DECODER = new ByteArrayDecoder();
private static final ByteArrayEncoder ENCODER = new ByteArrayEncoder();
@Autowired
@Qualifier("socketServerHandler")
private ChannelInboundHandlerAdapter socketServerHandler;
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// Add the text line codec combination first,
pipeline.addLast(new DelimiterBasedFrameDecoder(1024 * 1024, Delimiters.lineDelimiter()));
// the encoder and decoder are static as these are sharable
pipeline.addLast(DECODER);
pipeline.addLast(ENCODER);
pipeline.addLast(socketServerHandler);
}
}
以下是处理程序的一部分:
@Override
protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
ByteBuffer byteBuffer = ByteBuffer.wrap(msg).asReadOnlyBuffer();
}
答案 0 :(得分:0)
魔法就在这个班级
public class LogRecordDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
LogRecord logRecord = null;
byte[] bytes = new byte[in.readableBytes()];
int readerIndex = in.readerIndex();
in.getBytes(readerIndex, bytes);
ObjectInputStream ois = null;
ByteArrayInputStream inn = new ByteArrayInputStream(bytes);
try {
ois = new ObjectInputStream(inn);
logRecord = (LogRecord) ois.readObject();
out.add(logRecord);
} catch (Exception e) {
}
}
}