我目前正在研究一个小型聊天程序。

到目前为止,这是服务器类的重要部分,它将启动一个线程来侦听客户端输入:

Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream());

while (true) {
    if ( in .hasNextLine() && clientName == null) {
        clientName = in .nextLine();
    }
    if ( in .hasNextLine()) {
        String input = in .nextLine();
        out.println(clientName + ":  " + input);
        out.flush();
    }
}


但是,这一直在循环。我希望它等待输入,并暂停线程直到发生这种情况。是否有一个内置函数供Scanner等待下一行,而不是检查是否有一行然后返回true或false?

最佳答案

只需删除hasNextLine调用,nextLine就会阻止。

10-07 19:05
查看更多