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.socketAdd, timeOut);
This I am trying on a web application. When a user makes a request, I am passing values to socket server, but if I don't receive any response in 5 secs the socket should disconnect. But in my case the whole request is getting submitted once again. Can any one please tell me where am I going wrong?
I want to cut the socket connection, if I don't get any response in 5 secs. How can I set it? Any sample code would help.
Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);
socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.
Using try/catch/finally If you are a developer, so you can surround the socket connection part of your code in a try/catch/finally and handle the error in the catch. You might try connecting a second time, or try connecting to another possible socket, or simply exit the program cleanly.
You can even try for :
Socket client=new Socket(); client.connect(new InetSocketAddress(hostip,port_num),connection_time_out);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With