从socket InputStream创建的BufferedReader中的readLine()!= null循环永远不会退出

时间:2016-03-08 23:02:50

标签: java sockets inputstream bufferedreader

我正在使用InputStream从套接字BufferedReader逐行读取输入,但在while循环之后似乎没有执行任何操作。套接字来自accept()上的ServerSocket而不是Socket link = new Socket(address, 80);之类的内容。

代码

        String input;
        BufferedReader in = null;
        DataOutputStream out = null;
        boolean foundConnectionHeader = false;
        try {
            in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            out = new DataOutputStream(connectionSocket.getOutputStream());

            // Change keep alive connection header to close, add connection header if it doesn't exist
            while ((input = in.readLine()) != null) {
                if (foundConnectionHeader) {
                    requestHeaders.add(input);
                } else {
                    if (input.contains("Proxy-Connection: keep-alive")) {
                        requestHeaders.add("Proxy-Connection: close");
                        foundConnectionHeader = true;
                    } else {
                        requestHeaders.add(input);
                    }
                }
//              System.out.println(input);
            }
            if (!foundConnectionHeader) {
                requestHeaders.add("Proxy-Connection: close");
            }

            System.out.println("DONE");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:0)

当对等方断开连接时,它将返回null。

如果您要实施HTTP,则需要熟悉RFC 2616,尤其是有关内容长度和连接生命周期的部分。你现在的代码并不合适。