我试图使用客户机上的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];上,以及在main方法中调用readBytes()的位置。
任何帮助都将不胜感激!
编辑
我实际上得到了一些意想不到的结果。
17:50:14 Server waiting for Clients on port 1500. Thread trying to create Object Input/Output Streams 17:50:16 Client[0.7757499147242042] just connected. 17:50:16 Server waiting for Clients on port 1500. Byte array length: 16 Server recieved ciphertext: 27 10 -49 -83 127 127 84 -81 48 -85 -57 -38 -13 -126 -88 6 Server decrypted ciphertext to: asd 17:50:19 Client[0.7757499147242042] Byte array length: 1946157921
我在will循环中调用readBytes(),因此服务器将侦听通过套接字传输的任何内容。我想这是第二次尝试运行它,即使没有发送任何其他内容,而且len变量正以某种方式被设置为1946157921。这背后有什么逻辑呢?
发布于 2014-05-31 07:32:09
您一定是通过套接字发送了其他东西;没有按照您编写的方式读取它;因此,不同步。结果就是你读的长度不是真正的长度;太大了;当你试图分配它的时候,内存就用完了。错误不在这段代码中。当然,如果len == 0,则在读取时不应该分配bye数组。
我读过这篇文章,通常是因为没有冲洗DataOutputStream
事实并非如此。
len变量以某种方式被设置为1946157921。
就像预期的那样。QED
发布于 2014-06-01 12:03:04
您正在耗尽可用的堆。这方面的快速解决方案将增加(或缺少指定) JVM启动参数中的-Xmx参数,使其达到应用程序能够完成手头任务的程度。
发布于 2014-05-31 07:45:39
在控制台中使用-Xms1500m运行应用程序,在Netbeans中您可以在项目属性-> Run ->VM选项中找到它。
今天,我在内存中遇到了这个问题,在对Xms做了一些调整之后,我能够解决这个问题。检查它是否对您有效,如果有真正更大的东西,那么这将比您必须检查如何改进您的代码。
https://stackoverflow.com/questions/23967491
复制相似问题