Explanation of the difference between Connection timed out and Connection refused in Java

  • 2021-07-18 07:53:35
  • OfStack

Preface: When these two exceptions are reported, it shows that the client can't connect to the server normally, but there is still a difference between them.

1: Connection timed out

It is often encountered in actual development Connection timed out The question of


java.net.ConnectException: Connection timed out (Connection timed out)
  at java.net.PlainSocketImpl.socketConnect(Native Method)
  at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
  at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
  at java.net.Socket.connect(Socket.java:589)
  at java.net.Socket.connect(Socket.java:538)
  at java.net.Socket.<init>(Socket.java:434)
  at java.net.Socket.<init>(Socket.java:211)
  at ClientSocketTimeout.main(ClientSocketTimeout.java:8)

When you get Connection timed out: connect, it means that the route of TCP is abnormal. There are many reasons, which may be that the server cannot communicate with ping, the server (firewall, etc.) discards the request packet, the server responds too slowly, or there is an intermittent problem (in this case, it is difficult to troubleshoot the problem from the log file).

2: Connection refused

When you get Connection refused: connect  An exception indicates that the route from the local client to the target IP address is normal, but there is no process listening on the target port, and then the server rejects the connection.

A successful tcp link will see Syn, Syn-Ack and Ack, which is our expected TCP 3 handshakes. Connection refused will see Syn, Rst when the tcpdump or wireshark packet grabbing tool is used to detect an incoming request packet.

Connection refused Troubleshooting

1. Check whether the firewall is open, such as whether the firewall is open and the port is open

2. Check to see if the server is working properly

3. Check whether the port that the server listens on and the port that the client accesses is 1

jps | grep [appname]

netstat -anp | grep [pid]

4. ping hostname, telnet hostname port

5. Check that the client accesses hostname and port correctly

6. Check if 127.0. 0.1/localhost is used when the server listening port is host

Summarize


Related articles: