【问题标题】:Java Sockets - Hang on reading data from serverJava Sockets - 挂起从服务器读取数据
【发布时间】:2016-07-20 08:08:51
【问题描述】:

我目前正在使用套接字处理一个小的客户端/服务器任务。 可悲的是,当客户端应该读取服务器发送的“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();
    }
}

【问题讨论】:

  • 似乎没有建立连接。你的output 实例是什么?
  • 与服务器上的相同。我也在那里使用 PrintWriter。

标签: java sockets


【解决方案1】:

您的服务器一直在读取连接直到它被关闭(只有在这种情况下in.readLine()才会返回null)。

但是您的客户端不会关闭与服务器的连接。因此服务器卡在了while循环中。

解决方案:您必须在发送请求后关闭output 流。或者在服务器端检测请求的结束,而无需等待“流结束”限制。

【讨论】:

  • 注意:通常使用 HTTP 时,Content-Length: 标头会显示正文的长度和结束位置。详情请见:stackoverflow.com/questions/15991173/…
  • 如果我立即关闭连接,之后我将无法向客户端发送确认,还是我误解了什么?
  • 没关系,我现在明白了。在服务器端进行任何读取之前,我转移了行数。感谢您的帮助。
  • @ebyrob:我们讨论的是读取请求的代码,而不是响应。 AFAIR 在 HTTP 中,请求结束由两个空行指示。
【解决方案2】:

在您的服务器代码中:

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

您的服务器永远不会到达 writeToFile 行,因为套接字连接仍处于打开状态,并且仍处于 while 循环中。作为解决方案,请使用DataFetcher

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多