jgg
jgg

Reputation: 1136

java.net.SocketException Connection timed out error

I am getting below error when I am trying to connect to a TCP server. My programs tries to open around 300-400 connections using diffferent threads and this is happening during 250th thread. Each thread uses its own connection to send and receive data.

java.net.SocketException: Connection timed out:could be due to invalid address
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:372)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:233)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:220)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:385)

Here is the code I have that a thread uses to get socket:

socket = new Socket(my_hostName, my_port);

Is there any default limit on number of connections that a TCP server can have at one time? If not how to solve this type of problems?

Upvotes: 1

Views: 14964

Answers (2)

user207421
user207421

Reputation: 311050

Why all the connections? Is this a test program? In which case be aware that opening large numbers of connections from a single client stresses the client in ways that aren't exercised by real systems with large numbers of different client hosts, so test results from that kind of client aren't all that valid. You could be running out of client ports, or some other client resource.

If it isn't a test program, same question. Why all the connections? You'd be better off running a connection pool and reusing a much smaller number of connections serially. The network only has so much bandwidth after all; dividing it by 400 isn't very useful.

Upvotes: 0

Chochos
Chochos

Reputation: 5159

You could be getting a connection timeout if the server has a ServerSocket bound to the port you are connecting to, but is not accepting the connection.

If it always happens with the 250th connection, maybe the server is set up to only accept 250 connections. Someone has to disconnect so you can connect. Or you can increase the timeout; instead of creating the socket like that, create the socket with the empty constructor and then use the connect() method:

Socket s = new Socket(); s.connect(new InetSocketAddress(my_hostName, my_port), 90000);

Default connection timeout is 30 seconds; the code above waits 90 seconds to connect, then throws the exception if the connection cannot be established.

You could also set a lower connection timeout and do something else when you catch that exception...

Upvotes: 5

Related Questions