How to set timeout on client socket connection?

后端 未结 3 1412
逝去的感伤
逝去的感伤 2020-12-29 03:15

I am trying to set the timeout of a connection on the client socket in java. I have set a default connect timeout to 2000, i.e:

this.socket.connect(this.soc         


        
相关标签:
3条回答
  • 2020-12-29 03:39

    You can even try for :

    Socket client=new Socket();   
    client.connect(new InetSocketAddress(hostip,port_num),connection_time_out); 
    
    0 讨论(0)
  • 2020-12-29 03:47

    To put the whole thing together:

    Socket socket = new Socket();
    // This limits the time allowed to establish a connection in the case
    // that the connection is refused or server doesn't exist.
    socket.connect(new InetSocketAddress(host, port), timeout);
    // This stops the request from dragging on after connection succeeds.
    socket.setSoTimeout(timeout);
    
    0 讨论(0)
  • 2020-12-29 03:48

    What you show is a timeout for the connection, this will timeout if it cannot connect within a certain time.

    Your question implies you want a timeout for when you are already connected and send a request, you want to timeout if there is no response within a certain amount of time.

    Presuming you mean the latter, then you need to timeout the socket.read() which can be done by setting SO_TIMEOUT with the Socket.setSoTimeout(int timeout) method. This will throw an exception if the read takes longer than the number of milliseconds specified. For example:

    this.socket.setSoTimeout(timeOut);
    

    An alternative method is to do the read in a thread, and then wait on the thread with a timeout and close the socket if it timesout.

    0 讨论(0)
提交回复
热议问题