做项目时发现使用如下方法初始化socket的时候普遍要花4、5秒才能正常联通(前提该IP和端口完全正常能通)
Socket s = new Socket("10.13.3.10", Integer.parseInt(ip_port));后来网上去查了一下,发现是Java代码把10.13.3.10这个IP识别成主机名了,然后通过DNS又解析不到,超时之后才解析成IP所以花了5秒,提供的解决方法是修改windows的host文件我尝试了一下可行,但是这个项目最终是要给客户的,我不可能让客户也去修改Host文件啊,请问大家谁知道有什么通过改代码就能搞定的解决办法吗?PS:尝试了new Socket(InetAddress.getByAddress(byte[] addr) , int port)还是不行
Socket s = new Socket("10.13.3.10", Integer.parseInt(ip_port));后来网上去查了一下,发现是Java代码把10.13.3.10这个IP识别成主机名了,然后通过DNS又解析不到,超时之后才解析成IP所以花了5秒,提供的解决方法是修改windows的host文件我尝试了一下可行,但是这个项目最终是要给客户的,我不可能让客户也去修改Host文件啊,请问大家谁知道有什么通过改代码就能搞定的解决办法吗?PS:尝试了new Socket(InetAddress.getByAddress(byte[] addr) , int port)还是不行
Socket(InetAddress address, int port)
InetAddress address = InetAddress.getByName("10.13.3.10");
当这样构造InetAddress的时候,是不会去查找dns的,只有显示调用getHostName时,才会查找dns
然后用socket(InetAddress,Port)试试
Elapsed :16 ms
Elapsed :47 ms我跑循环 10 次得到:
Elapsed :46 ms
Elapsed :0 ms
Elapsed :63 ms
Elapsed :16 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :15 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :16 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :15 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :16 ms
Elapsed :15 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :16 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :16 ms
Elapsed :0 ms
Elapsed :0 ms
Elapsed :15 ms
Elapsed :0 ms public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) { {
long before = System.currentTimeMillis(); InetAddress address = InetAddress.getByAddress(new byte[] { 64,
(byte) 233, (byte) 189, (byte) 147 }); Socket socket = new Socket(address, 80); long after = System.currentTimeMillis(); System.out.println("Elapsed :" + (after - before) + " ms"); socket.close();
} {
long before = System.currentTimeMillis(); Socket socket = new Socket("64.233.189.147", 80); long after = System.currentTimeMillis(); System.out.println("Elapsed :" + (after - before) + " ms"); socket.close();
} {
long before = System.currentTimeMillis(); Socket socket = new Socket("www.google.com", 80); long after = System.currentTimeMillis(); System.out.println("Elapsed :" + (after - before) + " ms"); socket.close();
}
}
}
2. 其次:new byte[] { 64, (byte) 233, (byte) 189, (byte) 147 }
3. 最慢:www.google.com.