Vibeeshan Mahadeva
Vibeeshan Mahadeva

Reputation: 7238

Getting end of Inputstream in java

following is my client side code , that retrieves text from server and prints.

Socket socket = new Socket(ip, port);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        String string = "Hello!\n";
        byte buffer[] = string.getBytes();
        out.write(buffer);


    while ((character = in.read()) != -1){
            System.out.print((char) character);
        }

I am getting the the correct values from the server , but it is happening again and again , how can i find out the length of the value sent.

Upvotes: 3

Views: 2290

Answers (1)

esaj
esaj

Reputation: 16035

-1 denotes the end of the stream, and is received when the connection is closed. If you want to keep the connection open and send multiple messages, you need some sort of protocol (kind of like agreement between both ends) that tells where the message ends. The are many ways to do this, but in your example you're writing a line terminator (\n) to the end of the message, so you could check for that at the other end. Another way is to write the amount of bytes you're about to send before the actual message contents.

Upvotes: 5

Related Questions