Doubts Socket Server

1

I have a question about the behavior of the code that is creating a socket server, follow the code of the server:

public class Server {

public static void main(String args[]){
    try {
        ServerSocket server = new ServerSocket(3322);                       
        System.out.println("Servidor iniciado na porta 3322");

        Socket cliente = server.accept();
        System.out.println("Cliente conectado do IP "+cliente.getInetAddress().
                getHostAddress());
        Scanner entrada = new Scanner(cliente.getInputStream());
        while(entrada.hasNextLine()){
            System.out.println(entrada.nextLine());
        }

        entrada.close();
        server.close();

    } catch (IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }

}

After the client connects to the server and for example does not type anything ... the input.hasNextLine () method should not return false thus closing while and closing the socket ? why does not this happen and the code stays "forever" waiting to receive messages typed by the client?

    
asked by anonymous 15.06.2018 / 15:51

1 answer

1

Because an operation involving typing via the keyboard is an infinite data input, that is, the system is eternally in wait for the next line to be typed, even if it never is. In other words, this method has the ability to block the execution of the rest of the program while waiting for the next input, which can never happen if the user decides not to enter anything else. The documentation makes this explicit:

  

public boolean hasNextLine ()

     

Returns true if there is another line in   the input of this scanner. This method may block while waiting for   input . The scanner does not advance past any input.

You could, in this case, check if the line is empty as an output condition of while .

    
15.06.2018 / 16:29