Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Socket creation takes more time

Tags:

java

sockets

I have given Socket soc = new Socket(host,port); Now when the host machine is up and in running state, the socket is getting created immediately.

But when the machine is turned off or rebooted then this line takes around 40 seconds to respond. I tried using soc.setSoTimeout(timeout); But this line is used after creation of Socket. Hence it doesn't help much.

Also this seems to be a bug in JAVA itself. http://bugs.sun.com/bugdatabase/view_bug.do;:YfiG?bug_id=5092063

I have tried few workarounds given in this link like adding the machine port and host name in the etc/hosts file. But it doesn't work. Because of this delay due to DNS resolution while socket creation, the response time of my system gets severely affected.

Any help would be greatly appreciated.

thanks, Sr

like image 567
sriram Avatar asked May 16 '11 07:05

sriram


People also ask

Is java socket TCP or UDP?

Yes, Socket and ServerSocket use TCP/IP. The package overview for the java.net package is explicit about this, but it's easy to overlook. UDP is handled by the DatagramSocket class.

How ServerSocket works in java?

ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used).

Why we use socket programming in java?

Sockets allow you to exchange information between processes on the same machine or across a network, distribute work to the most efficient machine, and they easily allow access to centralized data. Socket application program interfaces (APIs) are the network standard for TCP/IP.


1 Answers

Use the connect with timeout method

// create an unconnected socket
Socket soc = new Socket();
soc.setSoTimeout(SO_TIMEOUT); // if you like

// connect (with timeout)
soc.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT);
like image 200
dacwe Avatar answered Oct 02 '22 20:10

dacwe