I have several nodes acting as both servers and clients using Java's TCP sockets, i.e., Socket and ServerSocket. Each node uses persistent connections to communicate with 4 to 10 neighbors. However, sometimes a node (node1) may throw the following exception when trying to connect to another node (node2):
java.net.ConnectException: Connection refused
If I run netstat on node2, it shows that a TCP connection has been established with node1 on the appropriate port (61685, in this case).
tcp 0 0 (node2):61685 (node1):55150 ESTABLISHED
However, node1 throws the same exception every time it tries to connect.
The ServerSocket is created as follows:
void OpenRcvSocket(final int port) {
Thread rcvthread = new Thread () {
@Override
public void run () {
ServerSocket rcvlistener = null;
boolean running = true;
try {
rcvlistener = new ServerSocket(port);
while(running) {
Socket incoming = rcvlistener.accept();
new ConnectionHandler(incoming);
}
} catch (IOException ex) {
System.out.println(ex);
}
finally {
try {
rcvlistener.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
};
rcvthread.start();
}
The sending portion looks like this:
synchronized void SendMsg(String dest, Message myMsg) {
PrintWriter printwr = SendingConnectionList.get(dest);
try {
if(printwr == null) {
Socket sendsock = new Socket(dest, port);
printwr = new PrintWriter(sendsock.getOutputStream(), true);
SendingConnectionList.put(dest, printwr);
}
printwr.print(myMsg.MsgToString());
printwr.flush();
} catch (UnknownHostException ex) {
System.out.println(dest+": "+ex);
} catch (IOException ex) {
System.out.println(dest+": "+ex);
}
}
The strange thing is that these nodes usually don't refuse all incoming connections because out of 10 neighbors, 6 might actually be able to connect, whereas 4 are rejected. I doubt there are firewalls running on all the of the nodes that I've tried and am pretty sure the service is running on the port. Is there any other reason this exception would be thrown? Thanks!