我正在编写一个用于通过Java用套接字2种方式发送文件的类这是on GitHub。一切正常,直到文件接收完成。很快:
在客户端上:
byte[] bytes = new byte[(int)forSend.length()];
InputStream fin = new FileInputStream(forSend);
int count;
while ((count = fin.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
fin.close();
fout = new FileOutputStream(filename);
byte[] bytes = new byte[length];
System.out.println("receiving file...");
int count;
while ((count = in.read(bytes)) > 0) {
fout.write(bytes, 0, count);
}
fout.flush();
fout.close();
[当我尝试添加用于在此后向套接字写入内容的代码时,启动后服务器和客户端正在等待某些内容(我不知道什么)
[以前,当我丢失一个DataInputStream读取(从服务器发送的消息,但客户端上没有此消息的接收者)时遇到了这种情况。但是目前我正在尝试添加标志,该标志在文件传输完成后会更改,并在以后检查其状态。它在服务器和客户端上都可以使用,但是添加对Socket的读/写操作后,我又回到了服务器和客户端都在等待的情况。
现在怎么了?
[我的朋友Denr01帮助了我,所以我的错误是控制文件长度,我的问题中没有任何地方。因此,我的“完成”确认已写入文件。解决问题的方法在发件人中:
int read = 0;
int block = 8192;
int count = 0;
byte[] bytes = new byte[block];
while (read != forSend.length()) {
count = fin.read(bytes, 0, block);
out.writeInt(count);
out.write(bytes, 0, count);
read += count;
System.out.println("already sent " + read + " bytes of " + forSend.length());
}
在发件人中:
int block = 8192;
int count = 0;
int read = 0;
byte[] bytes = new byte[block];
System.out.println("recieving file...");
while (read != length) {
block=in.readInt();
in.readFully(bytes, 0, block);
fout.write(bytes, 0, block);
read += block;
System.out.println("already recieved " + read + " bytes of " + length);
}
在这种情况下,我们可以控制每个文件的读取迭代,并且始终知道要接收多少字节,因此,当接收到的所有字节都相同时,下一个“消息”将不会写入文件。