2012-05-28 41 views

回答

2

它们是相同的:

Java源代码:

public 
class Socket { 

... 

    public Socket(String host, int port) 
    throws UnknownHostException, IOException 
    { 
    this(host != null ? new InetSocketAddress(host, port) : 
     new InetSocketAddress(InetAddress.getByName(null), port), 
     (SocketAddress) null, true); 
    } 


    public Socket(InetAddress address, int port) throws IOException { 
    this(address != null ? new InetSocketAddress(address, port) : null, 
     (SocketAddress) null, true); 
    } 

... 
} 
+0

谢谢,这是有益的。 – zhoubo

+0

InetSocketAddress中显示了差异。第一个构造函数InetSocketAddress(String,int)比另一个构造函数InetSocketAddress(InetAddress,int)需要更多时间,因为它需要验证String是否是一个合适的inet地址。 OpenJDK的源代码可在http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/net/InetSocketAddress.java#InetSocketAddress – andyandy

0

对于HelloWorld型项目没有他们太大的区别。在较大的项目中,使用方法1可能会有一些优势。如果您已经有InetAddress对象,那么通过使用Socket(InetAddress,int)构造函数可以避免让Socket类检查字符串是否是适当的Internet地址。

相关问题