Java 从TCP连接读取字节数组时服务器抛出OutOfMemory异常
我还在我的推送服务器上工作!我已经成功地使用javax.crypto.cipher实现了加密。这需要我将字节读/写到套接字的流中。我可以很好地发送和接收。加密有效。但是,当没有任何消息通过广播时,服务器抛出OutOfMemoryException。readBytes函数是:Java 从TCP连接读取字节数组时服务器抛出OutOfMemory异常,java,tcp,out-of-memory,server-push,Java,Tcp,Out Of Memory,Server Push,我还在我的推送服务器上工作!我已经成功地使用javax.crypto.cipher实现了加密。这需要我将字节读/写到套接字的流中。我可以很好地发送和接收。加密有效。但是,当没有任何消息通过广播时,服务器抛出OutOfMemoryException。readBytes函数是: public static byte[] readBytes() throws IOException { int len = dis.readInt(); byte[] data = new byte[le
public static byte[] readBytes() throws IOException {
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
return data;
}
调用此函数的代码是:
public String read() {
byte[] encrypted,decrypted = null;
try {
encrypted = readBytes();
if (encrypted.equals(new Byte[] {0})) return "";
if (encrypted.equals(null)) return null;
cipher.init(Cipher.DECRYPT_MODE, key);
decrypted = cipher.doFinal(encrypted);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String afterEncryption = new String(decrypted);
return afterEncryption;
}
在while循环中调用read():
while (true&loggedin&((inputLine=read())!=null)) {
引发的异常是:
Exception in thread "ServerThread" java.lang.OutOfMemoryError: Java heap space
at ServerThread.readBytes(ServerThread.java:277)
at ServerThread.read(ServerThread.java:245)
at ServerThread.run(ServerThread.java:108)
第277行声明字节数组。发送字节数组的函数是:
public static 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);
if (len > 0) {
dos.writeInt(len);
dos.write(myByteArray, start, len);
}
}
publicstaticvoidsendbytes(byte[]myByteArray,int start,int len)引发IOException{
if(len<0)
抛出新的IllegalArgumentException(“不允许负长度”);
如果(开始<0 | |开始>=myByteArray.length)
抛出新的IndexOutOfBoundsException(“超出范围:+start”);
如果(len>0){
dos.writeInt(len);
写(myByteArray,start,len);
}
}
sendBytes仅在read()停止阻塞时运行。这就是循环的工作原理
如果这段代码看起来很熟悉,那是因为我在堆栈溢出上找到了它
握手的工作原理完美无瑕,但一旦它停止发送东西,我会在大约五秒钟后收到异常
感谢您能给我的任何帮助。您几乎肯定会在协议中失去同步,并像读取一个长单词一样读取数据。在发送和接收时跟踪字长和字节数组长度,并进行匹配
为此,您应该认真研究使用CipherInputStream和CipherOutputStream:它们为您做了大量的繁重工作。甚至SSL。您可以打印
len
的值,或者在声明字节[]数据之前设置断点吗?很明显,它非常庞大(数以亿计)。你能提供更多的代码来使用吗?我认为现在的情况是readBytes被调用的次数太多了。所有其他代码都无关紧要。这就是所有事情发生的地方。问题不在于while循环被封装的代码,我认为Read并不是像它应该阻塞的那样吗?LeN似乎在一个点上设置为218762506,这让我想知道读写字节是否被称为“过早”导致它在响应的中间读取?你是对的,但是为什么当我说“代码> Read Stor()时?
它有效?@OsmiumUSA表明发送的是一个短字符,而不是int。你不认为吗?是的,但是sendBytes()
正在执行writeInt()
所以另一端的适当检索是readInt()
。此函数是否写入前面的零?逻辑规定它必须这样做,但我不确定了。@OsmiumUSA问题不在于你自己的代码做什么,而在于你的同伴给你发送了什么?writeInt()写入32位;writeShort()写16个字符。如果您的代码使用readShort(),则显然发送方使用的是writeShort()或其他以网络字节顺序写入16位的代码。在连接的两侧,读取和发送函数完全相同。这两个都是(应该)将整数写入流。我维护服务器和客户端,因此我知道这是事实。