【发布时间】:2020-03-16 20:25:56
【问题描述】:
我最近用 Java 编写了一个程序,它可以自动创建加密连接并传输有关它们的数据。现在我遇到的问题是,如果一次传输大量数据,输入流不再反应。 (我尝试一次传输 2016 个字节)
但我认为问题在于低字节传输。
服务器:
public byte[] read() throws IOException {
byte[] bytes = new byte[2];
this.inputStream.read(bytes);
int length = ((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff);
byte[] buffer = new byte[length];
this.inputStream.read(buffer);
return this.encryption.decryptAES(buffer);
}
客户:
public void write(byte[] message) throws IOException {
byte[] bytes = new byte[2];
message = this.encryption.encryptAES(message);
bytes[1] = (byte) (message.length & 0xFF);
bytes[0] = (byte) ((message.length >> 8) & 0xFF);
this.outputStream.write(bytes);
this.outputStream.write(message);
}
InputStreams 没有关闭或为空。 也没有抛出异常。
程序在读取服务器端字节数组长度的字节时挂起。在客户端,字节已成功发送。
【问题讨论】:
-
read()没有义务填充缓冲区,并且您忽略了它可能没有或确实可能已到达流末尾的两种情况。使用DataInputStream.readFully(),当您使用它时,使用它的readShort()方法,并在发件人处使用DataOutputStream.writeShort()。
标签: java arrays encryption stream byte