我正在尝试使用客户端上的 DataOutputStream 和服务器上的 DataInputStream 通过套接字发送包含 16 个项目的字节数组。
这些是我用于发送/接收的方法。
public void sendBytes(byte[] myByteArray) throws IOException {
sendBytes(myByteArray, 0, myByteArray.length);
}
public void sendBytes(byte[] myByteArray, int start, int len) throws IOException {
if (len < 0)
throw new IllegalArgumentException("Negative length not allowed");
if (start < 0 || start >= myByteArray.length)
throw new IndexOutOfBoundsException("Out of bounds: " + start);
dOutput.writeInt(len);
if (len > 0) {
dOutput.write(myByteArray, start, len);
dOutput.flush();
}
}
public byte[] readBytes() throws IOException {
int len = dInput.readInt();
System.out.println("Byte array length: " + len); //prints '16'
byte[] data = new byte[len];
if (len > 0) {
dInput.readFully(data);
}
return data;
}
一切正常,我可以打印字节数组长度、字节数组(密文),然后解密字节数组并打印出我发送的原始明文,但在控制台中打印后,程序立即崩溃出现 OutOfMemoryError: Java heap space
。
我读到这通常是因为没有刷新 DataOutputStream,但我在 sendBytes 方法中调用它,因此它应该在发送每个数组后清除它。
编译器告诉我错误发生在 readBytes 内的 byte[] data = new byte[len];
行以及我调用 readBytes()
的地方在主方法中。
任何帮助将不胜感激!
编辑
我实际上得到了一些意想不到的结果。
17:50:14 服务器在端口 1500 上等待客户端。
线程尝试创建对象输入/输出流
17:50:16 客户端[0.7757499147242042]刚刚连接。
17:50:16 服务器在端口 1500 上等待客户端。
字节数组长度:16
服务器收到密文:27 10 -49 -83 127 127 84 -81 48 -85 -57 -38 -13 -126 -88 6
服务器解密密文为:asd
17:50:19 客户端[0.7757499147242042]
字节数组长度:1946157921
我在 while 循环中调用 readBytes()
,因此服务器将监听通过套接字传输的任何内容。我猜想它会尝试第二次运行它,即使没有发送任何其他内容,并且 len
变量以某种方式设置为 1946157921。这背后可能有什么逻辑?
最佳答案
您必须通过套接字发送其他内容;阅读方式与书写方式不同;所以变得不同步。结果是你读到的长度不是真实的长度;太大;当您尝试分配内存时,内存就会耗尽。错误不在这段代码中。当然,如果 len == 0,则在读取时不应分配 bye 数组。
I have read this is usually because of not flushing the DataOutputStream
事实并非如此。
len variable is somehow being set to 1946157921.
正如预测的那样。量子ED
关于Java DataOutputStream/DataInputStream OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23967491/