简体   繁体   English

当我使用输入流阅读器时,我无法在从缓冲阅读器读取数据后退出 while 循环

[英]when i used inputstream reader i can't exit from the while loop after reading the data from the buffered reader

 Socket socket = serverSocket.accept();
                    InputStream is = socket.getInputStream();
                    InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader br=new BufferedReader(isr);
                    String number;
                    list.clear();
                      while ((number=br.readLine())!=null){
                       list.add(number);

                        }

while i trying to read the data from the buffered reader,i got the data.But i can't exit from the while loop if number equals null.当我试图从缓冲读取器读取数据时,我得到了数据。但如果 number 等于 null,我无法退出 while 循环。

readLine() returns null at stream, and not before, and end of stream on a socket only occurs when the peer has closed the connection. readLine()在流处返回 null,而不是在此之前,并且仅在对等方关闭连接时才会发生套接字上的流结束。 Your expectations appear to be misplaced.你的期望似乎放错了地方。

It's because you are failing at understanding the readline function and your implementation of it.这是因为您未能理解 readline 函数及其实现。 You are reading data from your buffer and comparing the data to null, which is obviously not what you are wanting.您正在从缓冲区读取数据并将数据与空值进行比较,这显然不是您想要的。 So here is how I like to read data from a TCP socket.所以这就是我喜欢从 TCP 套接字读取数据的方式。

while(statement == true){
    int count = bufferedInputStream.read(buffer);
    if (count == -1){
        // Socket has been closed
    } else {
        // Data has been read.
        // Do comparison here.
    }
}

Hope this helps.希望这可以帮助。

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

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