我遇到以下代码问题。
如果我使用ObjectOutputStream,一切运行正常但是当我尝试使用CipherOutputStream时,我在服务器端遇到以下错误。
如果我发送一个文件,我就不会完全收到。 如果我发送了多个文件,则最后一个文件没有完全收到,但前面的文件是。
它可能是什么?
我见过其他帖子,但他们没有帮助我。
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:128)
at myCloudServer$myCloudServerThread.run(myCloudServer.java:257)
客户端代码。发送文件。
SocketFactory socketFactory = SSLSocketFactory.getDefault();
clientSocket = socketFactory.createSocket(serverAddress[0], Integer.parseInt(serverAddress[1]));
ObjectInputStream objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
[...]
byte[] buffer = new byte[1024];
objectOutputStream.writeObject(sendingClientFiles.size());
for (File sendingClientFile : sendingClientFiles) {
[...]
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKeyEncrypt = keyGenerator.generateKey();
Cipher cipherEncrypt = Cipher.getInstance("AES");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeyEncrypt);
CipherOutputStream cipherOutputStream = new CipherOutputStream(objectOutputStream, cipherEncrypt);
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sendingClientFile));
int count = 0;
while ((count = bufferedInputStream.read(buffer, 0, buffer.length)) != -1) {
//objectOutputStream.write(buffer, 0, count);
cipherOutputStream.write(buffer, 0, count);
}
bufferedInputStream.close();
//objectOutputStream.flush();
cipherOutputStream.flush();
}
服务器代码。收到文件。
ServerSocketFactory serverSocketFactory = SSLServerSocketFactory.getDefault();
serverSocket = serverSocketFactory.createServerSocket(port);
Socket clientSocket = serverSocket.accept();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(clientSocket.getInputStream());
[...]
byte[] buffer = new byte[1024];
int i = 0;
int receivingClientFiles = (int) objectInputStream.readObject();
while(i < receivingClientFiles) {
[...]
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(diretorio + "/" + fileName));
int count = 0;
int received = 0;
while (received < fileLength) {
count = objectInputStream.read(buffer, 0, buffer.length);
bufferedOutputStream.write(buffer, 0, count);
received += count;
}
//while ((count = objectInputStream.read(buffer, 0, buffer.length)) != -1) {
// bufferedOutputStream.write(buffer, 0, count);
//}
bufferedOutputStream.close();
i++;
}
答案 0 :(得分:0)
在count = objectInputStream.read(buffer, 0, buffer.length);
中,您应该最大化文件大小(因为您可能会从下一个文件中读取字节)。并且该特定文件大小必须是流的加密长度,而不是原始文件大小(如果它们不同,那就是)。