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

标签 java file bufferedinputstream bufferedoutputstream

我正在编写一个具有客户端和服务器的程序,其中客户端将向服务器发送 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/

相关文章:

java - 如何读取服务器套接字 JAVA 中的所有 Inputstream

java - 如何访问 BufferedInputStream pos 和 markpos 变量?

java - 仅获取响应代码而不是 url 的完整来源

java - Socket 程序中的错误,发送空白消息并且每条消息之前都有一些奇怪的符号

javascript - 指定文件上传路径

iphone - 高效使用 NSData

java - 使用新 key 对创建临时 SSL/TLS 套接字

java - 使用 Runtime.exec 和 Putty 私钥连接到远程 Linux 系统

java - 文件对象和不同的 NetBeans 包

java - BufferedReader 与 BufferedInputStream 的性能衡量