Java通过套接字发送文件

问题描述 投票:0回答:1

我正在编写一个用于通过Java用套接字2种方式发送文件的类这是on GitHub。一切正常,直到文件接收完成。很快:

  • 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();
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的读/写操作后,我又回到了服务器和客户端都在等待的情况。

现在怎么了?

java file sockets transfer
1个回答
0
投票

[我的朋友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());
}
  1. 发送方读取字节并写入字节数
  2. 它将计数发送给接收者,因此接收者将知道在当前循环迭代中要接收多少字节
  3. 然后发送方发送字节块并增加读取的字节计数器
  4. 计数器不等于文件长度时重复此操作

在发件人中:

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);
}
  1. 使字节数组的长度等于发送方的块长度
  2. 在每次迭代中,首先读取下一个块长度,然后读取此字节数
  3. 收款人柜台
  4. 当计数器不等于先前收到的文件长度时重复此操作

在这种情况下,我们可以控制每个文件的读取迭代,并且始终知道要接收多少字节,因此,当接收到的所有字节都相同时,下一个“消息”将不会写入文件。

© www.soinside.com 2019 - 2024. All rights reserved.