【发布时间】:2015-09-23 23:11:20
【问题描述】:
我正在尝试构建一个客户端/服务器程序,它工作正常。当我发送一条消息时,它会显示在服务器上,然后它等待来自服务器的响应,但是在等待响应时我什么也做不了。
我的问题是:我怎样才能在后台等待响应,而我仍然可以发送消息并在发送时只显示服务器消息(如果已发送)。
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?
}
}
}
【问题讨论】:
-
它称为线程。 javas 套接字被设计为阻塞,因为你应该在不同的线程中运行它们。在那个线程中,您可以等待,当有事情发生时,您可以使用某种事件监听器将其返回到 ui(或控制台)。简而言之:查找java中的多线程教程
-
感谢您的回复