简体   繁体   English

Java中通过Socket进行文件传输,不会退出while循环

[英]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. 问题在于程序陷入了while循环,因此服务器无法执行其他任何操作。 There are no errors or anything... 没有错误或任何东西...

You never close the stream on the client side. 您永远不会在客户端关闭流。 Add dos.close() after dos.flush() ! dos.close()之后添加dos.close() dos.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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