gpt4 book ai didi

java - 聊天客户端一次只打印一行

转载 作者:行者123 更新时间:2023-11-30 11:39:54 26 4
gpt4 key购买 nike

我正在编写一个多线程聊天服务器/客户端,我一直在使用 SocketTest V 3 来测试服务器并且它似乎工作正常但是我编写的客户端只在我写新行时在控制台中更新,我我正在使用我自己的客户端进行套接字测试,每次写入内容时套接字都会更新,但我的客户端不会

public class clientV2 {


public static final int PORT = 5019;
public static InetAddress host;

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

try {
host = InetAddress.getLocalHost();
Socket socket = new Socket(host, PORT);

Scanner in = new Scanner(System.in);

Scanner inputFromServer = new Scanner(socket.getInputStream());

PrintWriter outputToServer = new PrintWriter(socket.getOutputStream());

while(true) {
if(inputFromServer.hasNext()) {
System.out.println(inputFromServer.nextLine());
}

String input = in.nextLine();
outputToServer.println(input);
outputToServer.flush();

}

} catch (Exception e) {

}
}

最佳答案

您的客户调用 nextLine()在它的扫描仪上,这个方法,正如它的名字所示,返回下一行。因此,在完整的下一行可用之前,您的客户无法打印任何内容。

这是 javadoc 对 nextLine() 的描述:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

关于java - 聊天客户端一次只打印一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12998947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com