Cbour
Cbour

Reputation: 59

setSoTimeout not working in java tcp connection

I have a server that connects with a client to receive a string, but when the connection is lost the server stays to the same condition and doesn't go back to the state in which it tries to make a connection again. I used setSoTimeout but it isn't working.

Here is my code :

ServerSocket welcomeSocket = null;
                Socket connectionSocket = null;
                BufferedOutputStream outToClient = null;

                try {
                    System.out.println("connecting to send "+fileToSend);

                    welcomeSocket = new ServerSocket(3249);
                    connectionSocket  = welcomeSocket.accept();



                    connectionSocket.setSoTimeout(10000);
                    welcomeSocket.setSoTimeout(10000);
                    outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());


                } catch (Exception ex) {
                    System.out.println("set so");
                    break;
                    // Do exception handling
                } 

Can someone please tell me why this is not throwing the exception?

Upvotes: 0

Views: 4401

Answers (1)

Perception
Perception

Reputation: 80603

You need to actually make a read call on clients input stream in order for the SO timeout to be triggered. And the exception will only be triggered if said read call blocks for longer than the timeout setting.

Also, its useless to set an SO timeout on the server socket, as you will never be 'reading' from it on the server side.

Upvotes: 3

Related Questions