Search code examples
javaloopsclientserversocket

ServerSocket Client While(True)


I have a question about While(true). Usually obliterates the CPU in a computer. Why in this instance does it not run constantly? And how can I get it to run if I need it to?

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);
        }
    }

Solution

  • Reading from a socket is a blocking operation (depending of the configuration of the socket and parameters in the call). In this case, the OS will block you until there is something to read in the socket.

    You could configure the socket to timeout the read operation if you need to.