ServerSocket Client While(True)



我有一个关于While(true(的问题。通常会消除计算机中的 CPU。为什么在这种情况下它不会持续运行?如果需要,我怎样才能让它运行?

public void startConnection() {
try {
client = new Socket(ip, port);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new 
InputStreamReader(client.getInputStream()));
out.println("Connection started from, " + client.getLocalAddress());
out.flush();
while (true) {
String recieve = in.readLine();
System.out.println(recieve);
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
String send = scan.nextLine();
if (send != null ) {
out.println(send);
out.flush();
}
}
} catch (Exception e) {
System.out.println(e);
JOptionPane.showMessageDialog(null, e.toString(), 
"Connection-Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}

从套接字读取是一种阻塞操作(取决于套接字的配置和调用中的参数(。在这种情况下,操作系统将阻止您,直到插槽中有要读取的内容。

如果需要,可以将套接字配置为使读取操作超时。

最新更新