Marijus
Marijus

Reputation: 4365

Socket client stuck on user input

So here's how my client looks like:

Socket socket = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

while (true) {
    String userInput = stdIn.readLine();
    if (userInput != null) {
        String message = username + ":" + userInput + "\n";
        out.println(message);
        out.flush();
    }

    String serverMessage = in.readLine();
    if (serverMessage != null){
        System.out.println(serverMessage);
    }
}

Client has to listen for user input to transmit it to other clients and has to listen for other clients messages. This code does exactly that but gets stuck on the first line listening for user input. Is there any workaround ?

Upvotes: 0

Views: 270

Answers (1)

Khanna111
Khanna111

Reputation: 3913

The reason that it gets stuck is that it waiting to read a line that was sent to this from the other end. There is nothing coming so it is getting stuck.

In order for it to not be stuck if there is no data forthcoming on it, you could set a socket timeout. Note that the socket will still be valid. Here it is:

socket.setSoTimeout(200); // Add this below the socket creation line. Timeout of 200 ms.

And

try {
    String serverMessage = in.readLine(); // it will timeout in 200 ms

    if (serverMessage != null) {
        System.out.println(serverMessage);
    }
} catch (SocketTimeoutException e) 
    // log
}

Please update the timeout to whatever is required but do make sure that it is not too little in that it would loop like crazy. Hope this helps.

Upvotes: 1

Related Questions