0

This is my TCP client java code:

socket = new Socket("127.0.0.1", 8088);
out = new DataOutputStream(socket.getOutputStream());
inputStream = socket.getInputStream();
inputReader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
while (inputStream != null) {
    result += inputReader.readLine();
}
out.writeUTF(result);
System.out.println(result);

socket.close();
out.close();

The while loop is getting executed infinitely.

I need a solution for this problem.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

3 Answers3

0

You need to check when readLine() returns null, not when inputStream becomes null (which it never will):

string s = inputReader.readLine();
while (s != null) {
    result += s;
    s = inputReader.readLine();
}

Or:

string s;
while ((s = inputReader.readLine()) != null) {
    result += s;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-1

You need to nullify your inputStream within the while loop with some condition, for it to break.

Sam
  • 111
  • 1
  • 5
-1

inputStream is always having a value i.e. its not null, so you keep looping and appending.

Does that make any sense? You can check like inputReader.readLine() != null instead:

string line;
while ((line=inputReader.readLine()) != null) {
    result += line;
}