java.net.UnknownHostException无法创建套接字。 Java的

时间:2018-05-06 13:23:44

标签: java sockets http

我阅读了一些手册并试图创建Socket,它在示例中看起来如何。

Socket socket = new Socket(InetAddress.getByName("http://google.com"), 80);

Socket socket = new Socket("http://google.com", 80);

无论如何,我得到了UnknownHostException:

java.net.UnknownHostException: http://google.com: Name or service not known

它将如何运作?

2 个答案:

答案 0 :(得分:1)

import java.io.*;
import java.net.*;

public class socket_client
{
    public static void main(String[] args) throws IOException 
    {
        Socket s = new Socket();
    String host = "www.google.com";

        try
        {
        s.connect(new InetSocketAddress(host , 80));
        }

        //Host not found
        catch (UnknownHostException e) 
        {
            System.err.println("Don't know about host : " + host);
            System.exit(1);
        }

        System.out.println("Connected");
    }
}

答案 1 :(得分:1)

尝试www.google.com。我刚试过telnet http://google.com并且它没有连接。然而,telnet www.google.com 80确实连接了。