Question

so i have this Java TCP Socket Client Application. Pretty Simple:

public class Main {

    public static void main(String argv[]) throws Exception {
        String hostName = "localhost";
        int portNumber = 5000;

        Socket echoSocket = new Socket(hostName, portNumber);
        PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        String userInput;
        while ((userInput = stdIn.readLine()) != null) {
            out.println(userInput);
            System.out.println("echo: " + in.readLine());
        }
        echoSocket.close();
    }
}

Now as you can see in the while loop, when a user enters something. It is sent to the server. Then the client waits for a response to the server. If the server is just echoing what the client inputs, this works perfectly!
"BUT" when the server doesn't respond with anything, my program just hangs...waiting for an input from the server forever.

So my question is, how can I modify the code so that when nothing is returned from the server, it doesn't stop?
Would I have to use threads? 1 from reading and sending client input, the other to print out responses from the server?

Was it helpful?

Solution

You can use setSoTimeout() on the socket:

Socket echoSocket = new Socket(hostName, portNumber);
echoSocket.setSoTimeout(10000); // Readings are timeouting after 10 seconds

From the javadoc:

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Parameters:

timeout the specified timeout, in milliseconds.

So, when you read the line, you can do that:

try {
    System.out.println("echo: " + in.readLine());
} catch (SocketTimeoutException ste) {
    // Do something
    System.out.println("nothing received");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top