1

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

此图像是服务器在顶部,客户端在底部的输出。那是我发现服务器卡住的地方。

在此处输入图像描述

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

4

1 回答 1

0

在您的客户端类中,尝试使用 while 循环替换write和运行flushobOut.close();

于 2017-09-15T21:50:56.333 回答