Read Data from a Java Socket

Looks like the server may not be sending newline characters (which is what the readLine() is looking for). Try something that does not rely on that. Here's an example that uses the buffer approach:

    Socket clientSocket = new Socket("www.google.com", 80);
    InputStream is = clientSocket.getInputStream();
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
    pw.println("GET / HTTP/1.0");
    pw.println();
    pw.flush();
    byte[] buffer = new byte[1024];
    int read;
    while((read = is.read(buffer)) != -1) {
        String output = new String(buffer, 0, read);
        System.out.print(output);
        System.out.flush();
    };
    clientSocket.close();

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).

Tags:

Sockets

Java

Tcp