gpt4 book ai didi

Java通过Socket发送文件

转载 作者:行者123 更新时间:2023-12-01 20:21:45 24 4
gpt4 key购买 nike

我正在编写一个类,用于通过Java中的套接字双向发送文件这里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 的读/写会让我回到服务器和客户端都在等待某些东西的情况。

现在出了什么问题?

最佳答案

我的 friend Denr01帮助了我,所以我的错误是文件长度的控制,我的问题中没有它的任何地方。因此,我的“完成”确认已写入文件。解决问题的方法在sender中:

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. 发送方读取字节并写入 count 个字节
  2. 它将计数发送给接收者,因此接收者将知道在当前循环迭代中接收多少字节
  3. 然后发送方发送字节 block 并增加读取的字节计数器
  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. 创建长度等于发送者 block 长度的字节数组
  2. 在每次迭代中首先读取下一个 block 长度,然后读取此字节数
  3. 增加接收者的计数器
  4. 当计数器不等于之前收到的文件长度时重复此操作

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

关于Java通过Socket发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com