Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set timeout on client socket connection?

Tags:

java

sockets

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.

like image 292
Vardhaman Avatar asked Apr 12 '11 08:04

Vardhaman


People also ask

How do I set socket timeout?

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);

What is socket connection timeout?

socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.

How do I fix socket timeout exception?

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.


1 Answers

You can even try for :

Socket client=new Socket();    client.connect(new InetSocketAddress(hostip,port_num),connection_time_out);  
like image 195
xyz Avatar answered Sep 21 '22 13:09

xyz