java BufferedReader readLine 方法挂起并阻塞程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7855822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:42:08  来源:igfitidea点击:

BufferedReader readLine method hangs and block program

javasockets

提问by Thiago Moraes

I'm trying to learn sockets using Java and I sucessfully sent data to a ServerSocket running in my own machine. When I try to read from this socket using readline (so I can just echo my own sent message) my program hangs and won't return.

我正在尝试使用 Java 学习套接字,并且成功地将数据发送到在我自己的机器上运行的 ServerSocket。当我尝试使用 readline 从这个套接字读取时(所以我可以只回显我自己发送的消息)我的程序挂起并且不会返回。

Here's the code:

这是代码:

public static void main(String[] args) throws UnknownHostException, IOException {

    TCPClient cli = new TCPClient("127.0.0.1", "15000");
    try {
        cli.ostream.writeUTF("Teste");
        String echo = cli.istream.readLine(); //it hangs in this line
        System.out.println(echo);
    }

TCPClient is a class I defined so I can test my program on a simpler interface before using swing on my homwework. here's the code:

TCPClient 是我定义的一个类,因此我可以在我的工作中使用 Swing 之前在更简单的界面上测试我的程序。这是代码:

public class TCPClient {

public DataOutputStream ostream = null;
public BufferedReader istream = null;

public TCPClient(String host, String port) throws UnknownHostException {
    InetAddress ip = InetAddress.getByName(host);

    try {
        Socket socket = new Socket(host, Integer.parseInt(port));

        ostream = new DataOutputStream(socket.getOutputStream());
        istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));


    } catch (IOException ex) {
        Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}

My server is pretty simple. After the connection is estabilished, it enters in this loop and stays here until I close the client (because of the infinite loop). Afterwards, some exception handling returns it to the point before the connection started.

我的服务器很简单。连接建立后,它进入这个循环并一直停留在这里直到我关闭客户端(因为无限循环)。之后,一些异常处理将其返回到连接开始之前的点。

            while(true){
                String msg = istream.readLine();
                System.out.println("Arrived on server: " + msg); //just works on debug
                ostream.writeUTF("ACK: " + msg);
                ostream.flush();
            }

I don't see what am I missing.

我不明白我错过了什么。

PS: the wierd stuff is that if I debug the server, I can see the message arriving there (I can print it, for example), but this isn't possible if I just run this code. Does this have some concurrency relation I'm overlooking?

PS:奇怪的是,如果我调试服务器,我可以看到到达那里的消息(例如,我可以打印它),但是如果我只运行此代码,这是不可能的。这是否有一些我忽略的并发关系?

thx

谢谢

回答by JB Nizet

The problem is that readLinetries reading a line. It will not return the line until it's sure that the end of line has been reached. This means that it expects either a newline character, or the end of the communication. Since the server doesn't send any newline char and doesn't close the stream, the client waits indefinitely.

问题是readLine尝试阅读一行。在确定到达行尾之前,它不会返回该行。这意味着它需要换行符或通信结束。由于服务器不发送任何换行符并且不关闭流,客户端无限期地等待。

回答by Ashwinee K Jha

cli.ostream.writeUTF("Teste");

Shouldn't this be containing a new line? Otherwise read method will be waiting for new line I think.

这不应该包含一个新行吗?否则我认为 read 方法将等待新行。

Also as suggested you can try flushing the ostream after writing to it.

同样按照建议,您可以在写入后尝试刷新 ostream。

回答by user207421

writeUTF() doesn't write a line. See the Javadoc. writeUTF() is for use with readUTF(). And Readers are for use with Writers. So change the DataOutputStream to a BufferedWriter and call write() and then newline().

writeUTF() 不写一行。请参阅 Javadoc。writeUTF() 与 readUTF() 一起使用。Readers 供 Writers 使用。因此,将 DataOutputStream 更改为 BufferedWriter 并调用 write(),然后调用 newline()。