繁体   English   中英

ServerSocket客户端While(True)

[英]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);
        }
    }

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

您可以根据需要将套接字配置为使读取操作超时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM