Java Socket超时问题

public void connect(SocketAddress endpoint,int timeout)可以设置超时连接时间

但是为什么下述代码中打开注释行后,不会等待而立即报错呢?

public static void main(String[] args) throws IOException {
    long beginTime = 0;
    try {
      Socket socket = new Socket();
      //socket.bind(new InetSocketAddress("localhost", 7777)); //①
      beginTime = System.currentTimeMillis();
      socket.connect(new InetSocketAddress("255.255.255.0", 8888), 6000);
      socket.close();
      System.out.println("client end!");
    } catch (Exception e) {
      long endTime = System.currentTimeMillis();
      System.out.println(endTime - beginTime);
      e.printStackTrace();
    }
  }
阅读 2.8k
1 个回答

因为肯定不可达啊,已经绑定在本地环回地址的套接字了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题