aukxn
aukxn

Reputation: 231

Java - Using Scanner reading from Socket InputStream

I am sorry because I can't think of any better title. I has a server-client program written in java that server send a string that end with new line character \n the client read from socket.getInputStream() if input has next line by using Scanner

on server-side

ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
PrintWrite send = new PrintWriter(socket.getOutputStream);
send.print("Server has succeeded to proccess your request \n" + show(ID));
send.flush();

The show(ID) is a function that return a string which already contain next line character in it. on client side

Socket socket = new Socket(HOST,PORT);
Scanner read = new Scanner(socket.getInputStream);
public Boolean ServerResponse(){
    System.out.println("please wait");
    Boolean result=false;
    while(true){
        if(read.hasNextLine()){
            System.out.println("has next");
            String msg = read.nextLine();
            System.out.println(msg);
            if(msg.contains("succeeded")){
                result = true;
            }

        }else{
            System.out.println("finished reading server respone");
            return result;
        }

    }
}

when I tried to run this. "finished reading server respone" is never printed and there is no has next after the last line send by Server is printed which assume that there is no next line character. However the else block is never executed. Strangely when I terminate the Server, it is printed. Can anyone please explain this to me and what I must do that I don't need to terminate the server for that line to be printed?

Upvotes: 1

Views: 5056

Answers (2)

David SN
David SN

Reputation: 3519

You are probably not closing the PrintWriter in the server side.

As Socket and PrintWriter implements autoclosable interface, you can use a try with resources block to close the resources when the server has finished with them.

try (Socket socket = serverSocket.accept();
     PrintWriter send = new PrintWriter(socket.getOutputStream);) {
    send.print("Server has succeeded to proccess your request \n" + show(ID));
}

When you call the method hasNextLine in your scanner in the client side, it blocks waiting for input.

If you shutdown your server, the stream is closed and the method hasNextLine return false and the finished reading server response is displayed in the client.

Upvotes: 1

zubergu
zubergu

Reputation: 3706

From Scanner#hasNextLine documentation:

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.

Meaning that it will return true if next line is available, not that it will return false when no next line is available for processing. It might be waiting for another line to show up, though.

Upvotes: 2

Related Questions