首页 文章

Java DataOutputStream / DataInputStream OutOfMemoryError

提问于
浏览
1

我正在尝试使用客户端上的DataOutputStream和服务器上的DataInputStream在套接字上发送包含16个项目的字节数组 .

These are the methods I am using for sending/receiving.

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方法中调用它,所以它应该在每个数组发送后清除它 .

编译器告诉我 byte[] data = new byte[len]; 行上的readBytes内部发生了错误,并且我在main方法中调用了 readBytes() .

任何帮助将不胜感激!

Edit

我实际上得到了一些意想不到的结果

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

我在while循环中调用 readBytes() ,因此服务器将监听通过套接字传输的任何内容 . 我猜它试图再次运行它,即使没有其他任何东西被发送, len 变量以某种方式设置为1946157921 . 这可能背后的逻辑是什么?

3 回答

  • -1

    您的可用堆已用尽 . 对此的快速解决方案是将JVM启动参数中的-Xmx参数增加(或指定缺失)到应用程序能够完成手头任务的级别 .

  • 0

    在控制台中使用-Xms1500m运行应用程序,在Netbeans中可以在项目属性 - >运行 - > VM选项中找到它 .

    我今天遇到了这个内存不足的问题,经过一段时间用Xms调整后,我能够解决问题 . 检查它是否适用于您,如果有比这更大的东西,那么您必须检查如何改进您的代码 .

    Check discussion here

  • 3

    您必须通过套接字发送其他内容;不像你写的那样读它;所以不同步 . 效果将是你读的长度不是真正的长度;太大了;尝试分配时内存不足 . 该错误不在此代码中 . 当然,除非len == 0,否则在阅读时不应分配再见数组 .

    我读过这通常是因为没有刷新DataOutputStream

    事实并非如此 .

    len变量以某种方式设置为1946157921 .

    正如预测的那样 . QED

相关问题