Search code examples
javasocketstcp

Read data from a Java Socket


I have a Socket listening on some x port.

I can send the data to the socket from my client app but unable to get any response from the server socket.

BufferedReader bis = new BufferedReader(new 
InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = bis.readLine()) != null)
{
    instr.append(inputLine);      
}

This code part reads data from server.

But I can't read anything from server until unless the Socket on the server is closed. Server code is not under my control to edit something on it.

How can I overcome this from client code.

Thanks


Solution

  • To communicate between a client and a server, a protocol needs to be well defined.

    The client code blocks until a line is received from the server, or the socket is closed. You said that you only receive something once the socket is closed. So it probably means that the server doesn't send lines of text ended by an EOL character. The readLine() method thus blocks until such a character is found in the stream, or the socket is closed. Don't use readLine() if the server doesn't send lines. Use the method appropriate for the defined protocol (which we don't know).