Java 通过数据包将png从服务器发送到客户端:indexOutOfBoundsException
在尝试通过png从服务器发送到客户端时,我使用netty获得了一个indexOutOfBoundException。错误发生在读取客户端中字节Java 通过数据包将png从服务器发送到客户端:indexOutOfBoundsException,java,netty,packet,Java,Netty,Packet,在尝试通过png从服务器发送到客户端时,我使用netty获得了一个indexOutOfBoundException。错误发生在读取客户端中字节p.readBytes()的行上 Exception in thread "LWJGL Application" java.lang.IndexOutOfBoundsException: readerIndex(97) + length(199852) exceeds writerIndex(185453): PooledUnsafeD
p.readBytes()
的行上
Exception in thread "LWJGL Application" java.lang.IndexOutOfBoundsException: readerIndex(97) + length(199852) exceeds writerIndex(185453): PooledUnsafeDirectByteBuf(ridx: 97, widx: 185453, cap: 185453)
at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1395)
at io.netty.buffer.AbstractByteBuf.checkReadableBytes(AbstractByteBuf.java:1389)
at io.netty.buffer.AbstractByteBuf.readBytes(AbstractByteBuf.java:850)
at io.netty.buffer.AbstractByteBuf.readBytes(AbstractByteBuf.java:858)
at com.benberi.cadesim.client.codec.util.Packet.readBytes(Packet.java:79)
at com.benberi.cadesim.client.packet.in.ListAllMapsPacket.execute(ListAllMapsPacket.java:29)
服务器端:
@Override
public void encode() {
setPacketLengthType(PacketLength.MEDIUM); //
writeByte((byte)ServerConfiguration.getAvailableMaps().size());
for (int i=0; i<ServerConfiguration.getAvailableMaps().size(); i++)
{
String map = ServerConfiguration.getAvailableMaps().get(i).replace(".txt", "");
writeByteString(map);
String mapDir = String.format("maps/%s.png", map);
try {
File imageFile = new File(mapDir);
BufferedImage img = ImageIO.read(imageFile);
writeInt((int)imageFile.length()); //write size of image
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(img, "png", stream);
writeBytes(stream.toByteArray()); // write image; byte array
stream.flush();
stream = null;
} catch (IOException e) {
// e.printStackTrace();
writeInt(0);
}
}
setLength(getBuffer().readableBytes());
}
您的问题是您正在重新编码图像,从而更改文件大小。当您读取图像
ImageIO.read()
时,它可能会丢失元数据,然后当您使用ImageIO.write()
写入图像时,不能保证对其进行逐字节编码,与最初在磁盘上编码的完全相同。我建议直接从文件中复制字节:
File imageFile = new File(mapDir);
byte[] fileContent = Files.readAllBytes(imageFile.toPath());
writeInt((int)imageFile.length()); //this should be the same as fileContent.length
writeBytes(fileContent);
您的问题是您正在重新编码图像,从而更改文件大小。当您读取图像
ImageIO.read()
时,它可能会丢失元数据,然后当您使用ImageIO.write()
写入图像时,不能保证对其进行逐字节编码,与最初在磁盘上编码的完全相同。我建议直接从文件中复制字节:
File imageFile = new File(mapDir);
byte[] fileContent = Files.readAllBytes(imageFile.toPath());
writeInt((int)imageFile.length()); //this should be the same as fileContent.length
writeBytes(fileContent);
File imageFile = new File(mapDir);
byte[] fileContent = Files.readAllBytes(imageFile.toPath());
writeInt((int)imageFile.length()); //this should be the same as fileContent.length
writeBytes(fileContent);