Doubt Socket Server

Asked

Viewed 71 times

2

I have a question in the behavior of the chunk of a code that is creating a socket server, follows the server code:

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 enter anything... the.hasNextLine() input method should not return false thus ending the while and closing the socket? why this does not happen and the code is "forever" waiting to receive messages typed by the client?

1 answer

2


Because a keyboard typing operation is an infinite data input, that is, the system is eternally in a state of waiting for the next line to be typed, even if it is never actually typed. 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 may never happen if the user chooses not to type 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, in case, could check if the line is empty as the exit condition of the while.

  • humm this means that if nothing has been typed by the client the hasnextline() method does not return nor true nor false , he stands at this point awaiting some input?

  • @Mateusguilherme I edited my reply adding information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.