gpt4 book ai didi

java - 服务器和客户端发送文件Java

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:24 26 4
gpt4 key购买 nike

我正在编写一个具有客户端和服务器的程序,其中客户端将向服务器发送 img 文件。下面的代码适用于服务器,它将卡在 obIn.read 的 while 循环中。在最后一次运行时阻塞,因此它永远无法返回 -1 并中断循环。它确实打破了我的客户的循环。所以我尝试在客户端循环后刷新它,但它似乎没有任何好处。我不想关闭 obOut,因为这会反过来关闭我想保持打开状态的套接字。服务器端是从 obIn(作为实例变量的输入流)接收数据并将其写入我创建的文件的地方。

                  //server receives file
File file = new File("image/image.png");
BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
byte[] bytes = new byte[1000];
int c = 0;
while((c = obIn.read(bytes)) != -1) {
fileOut.write(bytes, 0, c);
fileOut.flush();
System.out.println(c);
}
System.out.println(c);
fileOut.close();
System.out.println("File Created");
<小时/>
                //Client
String imgPath = in.nextLine();
File file = new File(imgPath);

BufferedInputStream fileIn = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[1000];
int c = 0;
while((c = fileIn.read(bytes)) != -1) {
obOut.write(bytes, 0, c);
obOut.flush();
System.out.println(c);
}
obOut.write(bytes, 0, 1000);
obOut.flush();
System.out.println(c);
fileIn.close();
System.out.println("File Sent");

此图像是服务器在顶部、客户端在底部的输出。这就是我发现服务器被阻塞的地方。

enter image description here

Here是我找到此方法并尝试使其适用于我的设置的地方。这是我第一次使用流。

最佳答案

在您的客户端类中,尝试将 while 循环之外的 writeflush 函数替换为 obOut.close();

关于java - 服务器和客户端发送文件Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46247422/

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