当我尝试使用localhost 172.0.0.1运行以下代码时抛出异常:java.net.ConnectException:连接被拒绝:连接
channel = SocketChannel.open();
//172.0.0.1 is a non-existing server
channel.connect(new InetSocketAddress("172.0.0.1", 4342));
但是,当我使用私有地址运行它时,以下代码会阻塞,直到超时:
channel = SocketChannel.open();
//192.168.0.1 is a non-existing server
channel.connect(new InetSocketAddress("192.168.0.1", 4342));
请问为什么连接到localhost会导致连接在连接私有地址时抛出异常会阻塞?
我问这个是因为我希望connect()在我启动localhost服务器时阻塞,而connect()会在服务器启动时自动连接到服务器。
有没有办法让connect()在localhost地址上阻塞?
谢谢!
答案 0 :(得分:2)
拒绝连接意味着目标服务器主动拒绝连接,因为没有服务器侦听该端口。
当客户端没有收到服务器的响应时发生超时,例如服务器根本不存在,流量被某些防火墙阻塞等。
当端口被占用时,没有什么可以尝试连接并向我发送响应。您必须在客户端实施重试。