簡體   English   中英

Java套接字-堅持從服務器讀取數據

[英]Java Sockets - Hang on reading data from server

我目前正在使用套接字來處理一個小的客戶端/服務器任務。 可悲的是,當客戶端應讀取服務器發送的“ 200 OK File Created”時,該客戶端掛起。 有什么我忽略的嗎?

客戶:

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

服務器:

  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();
    }
}

您的服務器正在從連接中讀取數據,直到關閉為止(僅在這種情況下in.readLine()將返回null )。

但是,您的客戶端不會關閉與服務器的連接。 因此,服務器被困在while循環中。

解決方案:發送請求后,您必須關閉output流。 或者,在服務器端檢測請求的結束,而無需等待“流的結束”限制。

在您的服務器代碼中:

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

您的服務器永遠不會進入writeToFile行,因為套接字連接仍處於打開狀態,並且仍處於while循環中。 作為解決方案,請使用DataFetcher

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM