Server and Client sending file Java

134 Views Asked by At

I am writing a program that has a client and server where the client will send a img file to the server. The code below is for the server where it will get stuck on that while loop from obIn.read blocking on its last run, so it never is able to return -1 and break the loop. It does break the loop for my Client. So I tried to flush it after the loop on the Client but it doesn't seem to do any good. I don't want to close obOut because that will in return close the socket which I want to keep open. The server end is where it receives the bites from the obIn(inputstream that is an instance variable) and writes it to a file that I have created.

                  //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");

This image is the output where the server is on top and the client is on bottom. That is where I found that the Server is stuck blocking.

enter image description here

Here is where I found this method and tried making it work for my setup. This is my first time working with streams.

1

There are 1 best solutions below

0
On

In your client class try replacing write and flush function out side of while loop with obOut.close();