socket详解

打开socket源码,发现socket有很多重载的构造方法,大部分构造方法都需要传链接地址和端口

  public Socket(InetAddress address, int port) throws IOException {

        this(address != null ? new InetSocketAddress(address, port) : null,

             (SocketAddress) null, true);

    }

  public Socket(String host, int port, InetAddress localAddr,

                  int localPort) throws IOException {

        this(host != null ? new InetSocketAddress(host, port) :

               new InetSocketAddress(InetAddress.getByName(null), port),

             new InetSocketAddress(localAddr, localPort), true);

    }

socket默认是向远程发起链接,若链接成功则返回socket,否则抛出异常,timeout指定链接超时时间

 public Socket(InetAddress address, int port, InetAddress localAddr,

                  int localPort) throws IOException {

        this(address != null ? new InetSocketAddress(address, port) : null,

             new InetSocketAddress(localAddr, localPort), true);

    }

InetAddress表示服务器地址或主机名,以及端口

InetAddress in = InetAddress.getLocalHost();

InetAddress in1 = InetAddress.getByName("www.taobao.com");

InetAddress[] ins = InetAddress.getAllByName("www.baidu.com");

 

你可能感兴趣的:(socket详解)