我还在推送我的推送服务器!我已经使用javax.crypto.cipher成功实现了加密。这需要我读取/写入套接字流的字节。我可以发送和接收就好了。加密工作。但是当没有任何内容传播时,服务器会抛出OutOfMemoryException。 readBytes函数是:
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);
}
}
sendBytes仅在read()停止阻塞时运行。这就是循环的设计方式。
如果这段代码看起来很熟悉,那是因为我发现堆栈溢出了!
握手完美无缺,但一旦停止发送,我就会在五秒钟后得到异常。
感谢您提供任何帮助。
答案 0 :(得分:0)
您几乎肯定会在协议和读取数据时失去同步,就好像它是一个长度的单词。在发送它们时跟踪长度字和字节数组的长度并接收它们并匹配它们。
你应该真正考虑使用CipherInputStream和CipherOutputStream:他们为你做了很多这项艰苦的工作。甚至是SSL。