user8143344
user8143344

Reputation:

Impossible to read from ouput stream

I have a server that sends a String to a socket client. When I try to get the contents of the String from the client it wouldn't read it. The server sends via:

output.write(res); output.flush(); // I checked res content and it is all good

and this the Client receiving:

public class Client {
public static void main(String[] args) throws IOException{
    Socket connexion = new Socket(InetAddress.getLocalHost(), 33333);

    BufferedReader input = new BufferedReader(
            new InputStreamReader(connexion.getInputStream(), "8859_1"), 1024);
    String res="";
    while(input.readLine()!=null){
        res += input.readLine()+"\n";
    }
    System.out.println(res);
}}

Suggestions please ? Thank you

Upvotes: 0

Views: 23

Answers (1)

Justin Albano
Justin Albano

Reputation: 3939

The problem is that you are reading the next line and then disregarding it, and then trying to read the next line again. The second time you read the next line, there is no data because the first read has already consumed it:

while(input.readLine()!=null){
    res += input.readLine()+"\n";
}

Try something like the following:

String line = null;
while((line = input.readLine()) != null) {
    res += line + "\n";
}

As @JB Nizet mentioned, this is contingent upon the server actually sending a newline character to the client to terminate the message. As stated in the documentation for readLine():

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Upvotes: 1

Related Questions