简体   繁体   中英

Java Sockets - Hang on reading data from server

I'm currently working on a little Client/Server task with using sockets. Sadly I the client hangs when it is supposed to read the "200 OK File Created" sent by the server. Is there anything i overlooked?

Client:

public HTTPClient(InetAddress adress, int portnumber, String filename) throws IOException {
    socket = new Socket(adress, portnumber);
    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    output = new PrintWriter(socket.getOutputStream());
    this.filename = filename;
}

public void sendPutRequest() throws IOException {
    output.println("PUT /" + filename + " HTTP/1.0");
    output.flush();
    File myFile = new File(this.filename);
    if (myFile.exists()) {
        for (String string : Files.readAllLines(myFile.toPath())) {
            output.println(string);
        }
        output.flush();
        String line;
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
    } else {
        throw new IOException("File not found");
    }
}

Server:

  try (Socket client = this.socket.accept(); 
    BufferedReader in = new BufferedReader(
    new InputStreamReader(client.getInputStream()));
    PrintWriter out = new PrintWriter(client.getOutputStream())) {

    String lineIn = in.readLine();
    if (lineIn.contains("PUT")) {
        String filename = lineIn.split(" ")[1].substring(1);
        List<String> filedata = new ArrayList<>();
        String line;
        while ((line = in.readLine()) != null) {
            filedata.add(line);
            System.out.println(line);
        }
        writeToFile(filename, filedata);
        out.println("200 OK File Created");
        out.flush();
    }
}

Your server is reading from the connection until it is closed (only in such a case in.readLine() will return null ).

However your client does not close the connection to the server. Therefore the server is stuck in the while loop.

Solution: You have to close the output stream after sending the request. Alternatively detect the end of the request on server side without waiting for the "end of stream" limit.

In your server code:

            while ((line = in.readLine()) != null) {
                filedata.add(line);
                System.out.println(line);
            }
             writeToFile(filename, filedata); // getting to this line?

Your server is never getting to the writeToFile line, because the socket connection is still open, and it's still in the while loop. As a solution, use DataFetcher

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