首页 > 技术文章 > Java 网络编程

ruhuanxingyun 2020-12-16 09:51 原文

1. 网络编程三要素

  A. IP地址:在网络上唯一标识一台计算机;

  B. 端口号:标识计算机上不同的应用程序,有效端口0-65535;

  C. 通讯协议:TCP和UDP。

2. 核心类

  A. InetAddress:互联网协议IP地址

public static void main(String[] args) {
    try {
        // 根据主机名或域名获取其IP地址
        InetAddress[] inetAddresses = InetAddress.getAllByName("www.hao123.com");
        for (InetAddress inetAddress : inetAddresses) {
            System.out.println("主机名:" + inetAddress.getHostName());
            System.out.println("IP地址:" + inetAddress.getHostAddress());
        }

        InetAddress inetAddress = InetAddress.getByName("www.hao123.com");
        System.out.println("主机名:" + inetAddress.getHostName());
        System.out.println("IP地址:" + inetAddress.getHostAddress());

        // 获取本地主机
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println("主机名:" + localHost.getHostName());
        System.out.println("IP地址:" + localHost.getHostAddress());
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}

  B. URL:统一资源定位符

public static void main(String[] args) {
    try {
        URL url = new URL("https://www.hao123.com/index.html");
        System.out.println("协议:" + url.getProtocol());
        System.out.println("主机名:" + url.getHost());
        System.out.println("端口号:" + url.getPort());
        System.out.println("资源路径:" + url.getPath());
        // 打开一个请求连接
        // url.openConnection();
        // 打开URL的连接并返回一个用于从该连接读入的InputStream
        // url.openStream();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  C. SocketAddress

  D. Socket

 

可参考:网络编程

    网络编程基本概念

推荐阅读