gpt4 book ai didi

Java套接字编程。如何在后台等待服务器响应?

转载 作者:行者123 更新时间:2023-12-01 19:26:58 25 4
gpt4 key购买 nike

我正在尝试构建一个客户端/服务器程序,它工作正常。当我发送消息时,它会显示在服务器上,然后等待服务器的响应,但在等待响应时我无法执行任何操作。

我的问题是:如何在后台等待响应,同时仍然可以发送消息并在发送时仅显示服务器消息(如果已发送)。

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


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

// Specify remote address and port
Socket cs = new Socket("localhost", 1337);
// Input and Output
DataInputStream dis = new DataInputStream(cs.getInputStream());
DataOutputStream dos = new DataOutputStream(cs.getOutputStream());

// Writing message to the server
String message = null;
Scanner scan = new Scanner(System.in);

while(true){
message = scan.nextLine();
if(message.equals("exit")) System.exit(0);
dos.writeUTF(message);
dos.flush();
// Check for messages from server ---> Here i wait for a message from the server but how can i wait in background without having my program freeze?
}
}

}

最佳答案

Java 中最简单的方法是在单独的线程中监听服务器数据。

将输入流设置为最终流,并在从控制台读取的 while 循环之前插入类似的内容:

new Thread() {
public void run() {
try {
while (true) {
System.out.println(dis.readUTF());
}
} catch(IOException e) {
e.printStackTrace();
}
}
}.start();

这会创建一个 Thread 的匿名子类,当调用 start 时,它将在后台执行 run 方法。

当您的代码增长时,您可能希望在单独的类中实现 Runnable 接口(interface),并将其交给 Thread 构造函数。

关于Java套接字编程。如何在后台等待服务器响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301942/

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