LoneCuriousWolf
LoneCuriousWolf

Reputation: 660

How to send reply from TCP server to TCP client?

I have following code for server and client. Client is able to send data to Server successfully but when Client tries to read data from server, code keeps on running without any output.

Server:

public static void main(String[] args) throws Exception {

    ServerSocket s = new ServerSocket(9898);

    while(true) {

        Socket recv = s.accept();

        InputStream inp = recv.getInputStream();
        OutputStream out = recv.getOutputStream();

        String data = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(inp));
        while ( (data = in.readLine()) != null ) {
            System.out.println("\r" + data);
        }

        out.write("sampleSendToClient".getBytes());
    }

}

Client:

public static void main(String[] args) throws Exception{
    Socket clientSocket = new Socket("localhost", 9898);
    OutputStream out = clientSocket.getOutputStream();
    InputStream inp = clientSocket.getInputStream();

    out.write("sampleSendToServer".getBytes());

    String data = null;
    //if I dont write next 4 lines then client exits gracefully 
    //but now it is stuck infinitely
    BufferedReader in = new BufferedReader(new InputStreamReader(inp));
    while ( (data = in.readLine()) != null ) {
        System.out.println("\r" + data);
    }

    clientSocket.close();
}

I am unable to understand what is wrong in above code.

Upvotes: 0

Views: 743

Answers (1)

L.Spillner
L.Spillner

Reputation: 1772

Quick but painless your server writes directly on the output stream by calling OutputStream#write(byte[] data) but your clients reads with a BufferedReader and BufferedReader#readLine() is a blocking I/O operation which will suspend his thread until a \n or \r character arrives on the InputStream (or the stream is closed in which case the method gets intererrupted an null is returned).

The String your server is sending does not end with \n or \r so the data may be sent already and linger in the buffere of the client's BufferedReader but without either of those terminating characters readLine() will never return.

Simply change

out.write("sampleSendToClient".getBytes());

to

out.write("sampleSendToClient\n".getBytes());

should do the trick.

Update:

while ( (data = in.readLine()) != null ) {
        System.out.println(data);
    }

This while loop will only exit if readLine() returns null this will only be the case if the stream is clsoed. However since you can't close the streams without losing the connection you will have to find another way to terminate the loop because now it will run forever.

Even after adding the \n your server wouldn't respond because he wil be infinitely loop at that point.


On a side note: For each new connection you're overwriting the previous socket without closing it's resources (primarly focused on the data stream and sockets themselves) and therefore creating ressource leaks. Consider to close every object when they are no longer needed.

Upvotes: 1

Related Questions