Java通过套接字发送文件
我正在编写一个类,用于在Java中通过套接字双向发送文件 给你。 在文件接收完成之前,一切都很好。 很快:Java通过套接字发送文件,java,file,sockets,transfer,Java,File,Sockets,Transfer,我正在编写一个类,用于在Java中通过套接字双向发送文件 给你。 在文件接收完成之前,一切都很好。 很快: 在client.java中,是以C:\Maven\README.txt的方式硬编码的 首先我发送文件名 然后我发送文件长度 在第三步中,我将文件从FileInputStream发送到DataOutputStream 在客户端: byte[] bytes = new byte[(int)forSend.length()]; InputStream fin = new FileInputS
- 在client.java中,是以C:\Maven\README.txt的方式硬编码的
- 首先我发送文件名
- 然后我发送文件长度
- 在第三步中,我将文件从FileInputStream发送到DataOutputStream
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();
- 服务器上的文件已完全接收(长度和内容相同)
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);
}
在这种情况下,我们可以控制每次文件读取迭代,并且始终知道要接收多少字节,因此,当接收到的所有字节相同时,文件中的下一条“消息”将不会写入文件。UPD:[ENG]我已尝试将读/写移出发送功能。如果客户端是发送方,服务器是接收方,则服务器会因EOFEException而崩溃。但我不知道是什么原因。[俄罗斯]。ааааааа,аааааа,аааа,ааааааааааааа。Но не догоняю чем он вызван.
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);
}