gpt4 book ai didi

java - 如何在使用 reader.readLine() 和 sc.nextLine() 时避免阻塞

转载 作者:行者123 更新时间:2023-12-02 10:40:24 29 4
gpt4 key购买 nike

我使用 reader.readLine()sc.nextLine() 来模拟服务器和客户端。然而,当我在扫描仪中输入一些文字后,服务器没有任何反应。我认为问题是线程阻塞,但我无法纠正它。谁能帮忙指出症结所在。

这是服务器的代码。

public class Server {

public static LocalDateTime currentTime() {
return LocalDateTime.now();
}
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(9091);
System.out.println("TCP server ready.\n");
Socket sock = ss.accept();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))) {
String cmd;
System.out.println("read in");
while ((cmd = reader.readLine()) != null) {
System.out.println("Rcvd: " + cmd);
if ("time".equals(cmd)) {
writer.write(currentTime() + "\n");
writer.flush();
} else {
writer.write("Sorry?\n");
writer.flush();
}
}
}
}
sock.close();
ss.close();

}

}

客户端代码

public class Client {

public static void main(String[] args) throws IOException, InterruptedException {
InetAddress addr = InetAddress.getLoopbackAddress();
try (Socket sock = new Socket(addr, 9091)){
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))){
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream(), StandardCharsets.UTF_8))){
Scanner sc = new Scanner(System.in);
String cmd;
while (sc.hasNext()) {
cmd = sc.nextLine();
System.out.println("Scanned: " + cmd);
writer.write(cmd);
writer.flush();

String resp = reader.readLine();
System.out.println("Response: " + resp);
}

}
}
}

最佳答案

在客户端中使用它:

writer.write(cmd + "\n");

因为服务器读取了行。

关于java - 如何在使用 reader.readLine() 和 sc.nextLine() 时避免阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950614/

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