博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Socket兼容IP和域名的原因
阅读量:3959 次
发布时间:2019-05-24

本文共 2630 字,大约阅读时间需要 8 分钟。

测试代码

//将172.16.12.171 替换为 xingyun25 打印结果一致Socket sock = new Socket("172.16.12.171",12331); InetAddress netAddress = sock.getInetAddress();System.out.println(netAddress.getHostName());System.out.println(netAddress.getHostAddress());sock.close();

打印结果

xingyun25172.16.12.171

查看 Socket 方法

public Socket(String host, int port) throws UnknownHostException, IOException    {
//host != null 因此第一个参数为new InetSocketAddress(host, port) this(host != null ? new InetSocketAddress(host, port) : new InetSocketAddress(InetAddress.getByName(null), //第二个参数 (SocketAddress) null //第三个参数 true (SocketAddress) null, true); }

查看 this 构造方法

private Socket(SocketAddress address, SocketAddress localAddr,                   boolean stream) throws IOException {
setImpl(); // backward compatibility if (address == null) throw new NullPointerException(); try {
createImpl(stream); if (localAddr != null) //localhost/127.0.0.1 bind(localAddr); //建立连接 connect(address); } catch (IOException | IllegalArgumentException | SecurityException e) {
try {
close(); } catch (IOException ce) {
e.addSuppressed(ce); } throw e; }}

对于 setImpl 方法

void setImpl() {    if (factory != null) {        impl = factory.createSocketImpl();        checkOldImpl();    } else {        // No need to do a checkOldImpl() here, we know it's an up to date        // SocketImpl!        impl = new SocksSocketImpl();    }    //Impl SET Socket     if (impl != null)        impl.setSocket(this);}

对于 createImpl 方法

// SocketImpl impl :The implementation of this Socket. void createImpl(boolean stream) throws SocketException {
if (impl == null) setImpl(); try {
impl.create(stream); created = true; } catch (IOException e) {
throw new SocketException(e.getMessage()); }}

查看InetSocketAddress方法通过IP和域名创建有何不同

public InetSocketAddress(String hostname, int port) {        checkHost(hostname);        InetAddress addr = null;		String host = null;        try {            addr = InetAddress.getByName(hostname);        } catch(UnknownHostException e){           host = hostname;        }        //实际构造了 InetSocketAddressHolder         holder = new InetSocketAddressHolder(host, addr, checkPort(port));    }

connect 过程中实际使用的是 InetAddress

private InetSocketAddressHolder(String hostname, InetAddress addr, int port) {
this.hostname = hostname; this.addr = addr; this.port = port;}

转载地址:http://yzozi.baihongyu.com/

你可能感兴趣的文章
js类型转换
查看>>
spring实例化Bean理解
查看>>
Mac下配置JAVA_HOME
查看>>
fedora 安装mp3播放器插件
查看>>
赏心悦目的宏代码
查看>>
理解套接字recv(),send()
查看>>
发一个C++写的跨平台的BlockingQueue
查看>>
Linux TCP/IP协议栈剖析【体系结构篇】
查看>>
游戏开发中预防内存泄露的一些措施
查看>>
以前的文章全部移除了。
查看>>
几首歌
查看>>
蝴蝶泉边
查看>>
编码转换
查看>>
freerice
查看>>
Does your mother know
查看>>
《写出质量好软件的75条体会》暨答案ZT [转自monkyy的blog]
查看>>
关于详细设计
查看>>
POJ2838,Sliding Window(单调队列)
查看>>
牛客练习赛50,B tokitsukaze and Hash Table(STL+输入输出挂)
查看>>
POJ3728,The merchant(倍增LCA+分治)
查看>>