Author |
Topic: java.net.ConnectException: Connection refused: connect |
|
EricJ member offline  |
|
posts: |
50 |
joined: |
02/22/2007 |
from: |
CA |
|
|
 |
|
|
java.net.ConnectException: Connection refused: connect |
How many connections to remote server can an application open concurrently? Let's take a look at the following code:
String HOST = "myServer";
int PORT = 1234;
InetAddress addr = InetAddress.getByName(HOST);
Socket socket = null;
try{
socket = new Socket(addr, PORT);
}catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
doSomethingWithThisConnection(socket);
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
The application simulates each connection by spawning a thread to run the above code to connect to remote server. Gradually increase the number of threads and once the number reaches certain number around 100, you would get somethings similar to the followings:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
|
|
|
|
|
|
|
EricJ member offline  |
|
posts: |
50 |
joined: |
02/22/2007 |
from: |
CA |
|
|
 |
|
|
"Connection refused" vs "Address already in use" |
Unlike "Address already in use" error which is caused by client side settings about maximum port can be mobilized during a certain amount of time, "Connection refused" is caused by server side settings which internationally rejected your connection for some reasons. Most likely, your client application is so aggressive in acquiring connection that the backlog queue of the remote server is full.
It's also interesting to note that "Address already in use" error happened in one thread environment and "Connection refused" error happened within multiple threads environment, even though they both try to open connection by calling the same code:
try{
socket = new Socket(addr, PORT);
}catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
|
|
|
|
|
|
|
EricJ member offline  |
|
posts: |
50 |
joined: |
02/22/2007 |
from: |
CA |
|
|
 |
|
|
How to Fix It? |
The maximum queue length of the server for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused. If your server is a popular and busy one, you may want to increase the backlog to 1000, for example:
ServerSocket sc = new ServerSocket(PORT, 1000);
|
|
|
|
|
|
|
|