简体   繁体   中英

Filetransfer over Socket in Java, wont go out of while-loop

I am trying to create a simple server-client-program where the user can upload and download files. I have got the Sockets and Streams to work, and I can upload a file to the server. But whenever one file has been uploaded the Server-side seems to get stuck in the loop that reads the streams and forwards it to the Server-file.

Server Code:

    InputStream in = clientSocket.getInputStream();

    String filePath = "......."
            + op[1];

    System.out.println(op[0] + ": " + filePath);

    FileOutputStream out = new FileOutputStream(filePath);

    byte[] bytes = new byte[16*1024];

    int count;

    while ((count = in.read(bytes)) > 0) {
        out.write(bytes, 0, count);
    }

Client Code:

    String filePath = "...."
            + path;
    System.out.println("Attempting: " + filePath);

    dos = new DataOutputStream(serverSocket.getOutputStream());
    fis = new FileInputStream(filePath);

    byte[] buffer = new byte[4096];

    while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }

    dos.flush();
    fis.close();

The problem is that the program gets stuck at the while-loop, so the Server can not perform anything else. There are no errors or anything...

You never close the stream on the client side. Add dos.close() after dos.flush() !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM