📜  Java网络

📅  最后修改于: 2022-05-13 01:54:20.384000             🧑  作者: Mango

Java网络

当笔记本电脑、台式机、服务器、智能手机和平板电脑等计算设备以及不断扩展的物联网小工具(例如相机、门锁、门铃、冰箱、音频/视频系统、恒温器和各种传感器)共享信息和数据时彼此之间称为网络。

Java网络教程

简而言之,术语网络编程或联网与编写可以在各种计算机设备上执行的程序相关联,其中所有设备都相互连接以使用网络共享资源。在这里,我们将讨论Java网络

  • 什么是Java网络?
  • 通用网络协议
  • Java网络术语
  • Java网络类
  • Java网络接口
  • 套接字编程
  • 内网地址
  • 网址类

什么是Java网络?

网络为简单的程序提供了很多功能。通过网络,单个程序可以重新获得存储在世界任何地方的数百万台计算机中的信息。 Java是一种领先的编程语言,从头开始就考虑到了网络。 Java Networking 是一种将两个或多个计算设备组合在一起以共享资源的概念。

所有Java程序在网络上的通信都是在应用层完成的。 J2SE API 的Java .net包包含执行低级通信功能的各种类和接口,使用户能够制定专注于解决问题的程序。



通用网络协议

如前所述, Java编程语言的Java .net包包括各种类和接口,它们提供了一种易于使用的方法来访问网络资源。除了类和接口之外, Java.net包还提供了对两种众所周知的网络协议的支持。这些是:

  1. 传输控制协议 (TCP) – TCP 或传输控制协议允许不同应用程序之间的安全通信。 TCP是一种面向连接的协议,这意味着一旦建立连接,数据就可以向两个方向传输。该协议通常用于 Internet 协议。因此,TCP 也称为 TCP/IP。 TCP 具有内置方法来检查错误并确保按发送顺序传输数据,使其成为传输静止图像、数据文件和网页等信息的完整协议。
  2. 用户数据报协议 (UDP) – UDP 或用户数据报协议是一种无连接协议,允许数据包在不同的应用程序之间传输。 UDP 是一种更简单的 Internet 协议,其中不需要错误检查和恢复服务。在 UDP 中,没有打开连接、维护连接或终止连接的开销。在 UDP 中,数据会不断地发送给接收者,无论他们是否收到。

Java网络术语

在Java Networking 中,经常使用许多术语。这些广泛使用的Java网络术语如下:

  1. IP 地址 – IP 地址是区分 Internet 或本地网络上的设备的唯一地址。 IP 代表“互联网协议”。它包含一组管理通过互联网或本地网络发送的数据格式的规则。 IP 地址是指可以修改的逻辑地址。它由八位字节组成。每个八位字节的范围从 0 到 255 不等。
    • IP 地址的范围 – 0.0.0.0 到 255.255.255.255
    • 例如 – 192.168.0.1
  2. 端口号 -端口号是一种在连接 Internet 或其他网络信息的特定进程到达服务器时识别该进程的方法。端口号用于唯一标识不同的应用程序。端口号充当应用程序之间的通信端点。端口号与IP 地址相关联,用于两个应用程序之间的传输和通信。有 65,535 个端口号,但并非每天都在使用。
  3. 协议 –网络协议是一组有组织的命令,用于定义数据在同一网络中的不同设备之间传输的方式。网络协议是用户可以轻松与世界各地的人们进行通信的原因,因此在现代数字通信中起着至关重要的作用。例如 – TCP、FTP、POP 等。
  4. MAC 地址 – MAC 地址代表媒体访问控制地址。这是分配给 NIC(网络接口控制器/卡)的奇怪标识符。它包含一个 48 位或 64 位地址,与网络适配器结合使用。 MAC 地址可以是十六进制组成。简而言之,MAC 地址是用于跟踪网络中设备的唯一编号。
  5. 套接字——套接字是网络上运行的两个应用程序之间双向通信连接的一个端点。套接字机制提供了一种进程间通信 (IPC) 方法,通过设置在其间发生通信的命名接触点。套接字与端口号相关联,以便 TCP 层可以识别数据要发送到的应用程序。
  6. 面向连接和无连接协议——在面向连接的服务中,用户必须在开始通信之前建立连接。连接建立后,用户可以发送消息或信息,之后就可以释放连接。但是,在无连接协议中,数据在从源到目的地的一条路由中传输,而无需验证目的地是否仍然存在或是否已准备好接收消息。在无连接协议中不需要身份验证。
    • 面向连接的协议示例 - 传输控制协议 (TCP)
    • 无连接协议示例 - 用户数据报协议 (UDP)

Java网络课程

Java编程语言的Java .net包包括各种类,这些类提供了一种易于使用的方法来访问网络资源。 Java.net包中涵盖的类如下:

  1. CacheRequest –当需要在 ResponseCache 中存储资源时,就会在Java使用 CacheRequest 类。此类的对象为 OutputStream 对象提供了一个边缘,以将资源数据存储到缓存中。
  2. CookieHandler CookieHandler 类在Java用于实现回调机制,以保护 HTTP 协议处理程序内部的 HTTP 状态管理策略实现。 HTTP 状态管理机制指定了如何进行 HTTP 请求和响应的机制。
  3. CookieManager CookieManager 类用于提供 CookieHandler 的精确实现。此类将 cookie 的存储与围绕接受和拒绝 cookie 的策略分开。 CookieManager 包含 CookieStore 和 CookiePolicy。
  4. DatagramPacket DatagramPacket 类用于提供一种工具,用于将消息从一个系统无连接传输到另一个系统。此类提供了用于应用数据报套接字类的无连接传输的数据报数据包的生成工具。
  5. InetAddress InetAddress 类用于提供获取任何主机名的 IP 地址的方法。 IP 地址由 32 位或 128 位无符号数表示。 InetAddress 可以处理 IPv4 和 IPv6 地址。
  6. 服务器套接字- ServerSocket 类用于实现客户端/服务器套接字连接的服务器端的独立于系统的实现。如果 ServerSocket 类的构造函数无法侦听指定端口,则会引发异常。例如 - 如果端口已被使用,它将抛出异常。
  7. Socket Socket 类用于创建帮助用户实现所有基本套接字操作的套接字对象。用户可以执行各种网络操作,例如发送、读取数据和关闭连接。使用Java.net.Socket类构建的每个 Socket 对象都与 1 个远程主机精确连接;为了连接到另一台主机,用户必须创建一个新的套接字对象。
  8. DatagramSocket DatagramSocket 类是一个网络套接字,它为发送和接收数据包提供无连接点。从数据报套接字发送的每个数据包都单独路由和传递。它可以进一步用于传输和接收广播信息。数据报套接字是 Java 的一种机制,用于通过 UDP 而不是 TCP 提供网络通信。
  9. 代理——代理是一个不变的对象,是一种工具、方法、程序或系统,用于保存其用户和计算机的数据。它的行为就像计算机和互联网用户之间的一堵墙。代理对象表示要应用于连接的代理设置。
  10. URL Java的 URL 类是 Internet 上任何可用资源的入口点。类 URL 描述了统一资源定位符,它是万维网上“资源”的信号。源可以表示简单的文件或目录,也可以表示更困难的对象,例如对数据库或搜索引擎的查询。
  11. URLConnection Java的 URLConnection 类是一个抽象类,描述由类似 URL 定义的资源连接。 URLConnection 类用于辅助两个不同但相互关联的目的。首先,它提供对与服务器(尤其是 HTTP 服务器)交互的控制,而不是 URL 类。此外,使用 URLConnection,用户可以验证服务器传输的标头,并可以做出相应的反应。用户还可以使用 URLConnection 配置客户端请求中使用的标头字段。

Java网络接口

Java编程语言的Java .net包包括各种接口,这些接口还提供了一种易于使用的方法来访问网络资源。 Java.net包中包含的接口如下:

  1. CookiePolicy – Java.net包中的 CookiePolicy 接口提供了用于实现各种网络应用程序的类。它决定哪些 cookie 应该被接受,哪些应该被拒绝。在 CookiePolicy 中,预定义了三种策略实现,即 ACCEPT_ALL、ACCEPT_NONE 和 ACCEPT_ORIGINAL_SERVER。
  2. CookieStore – CookieStore 是一个接口,用于描述 cookie 的存储空间。 CookieManager 将每个 HTTP 响应的 cookie 组合到 CookieStore,并为每个 HTTP 请求从 CookieStore 恢复 cookie。
  3. FileNameMap – FileNameMap 接口是一个简单的接口,它实现了一个工具来概述文件名和 MIME 类型字符串。 FileNameMap 从数据文件中收取文件名映射(称为 mimetable)。
  4. SocketOption – SocketOption 接口帮助用户控制套接字的行为。通常,在 Sockets 中开发必要的特性是必不可少的。 SocketOptions 允许用户设置各种标准选项。
  5. SocketImplFactory – SocketImplFactory 接口为 SocketImpl 实例定义了一个工厂。套接字类使用它来创建实现各种策略的套接字实现。
  6. ProtocolFamily——这个接口代表了一系列的通信协议。 ProtocolFamily 接口包含一个称为 name() 的方法,该方法返回协议族的名称。

套接字编程

Java Socket 编程用于在不同 JRE 上运行的应用程序之间进行通信。套接字使用 TCP 实现两台计算机之间的通信工具。 Java Socket 编程可以是面向连接的,也可以是无连接的。在 Socket Programming 中,Socket 和 ServerSocket 类被管理用于面向连接的套接字编程。但是,DatagramSocket 和 DatagramPacket 类用于无连接套接字编程。

客户端应用程序在其通信结束时生成一个套接字,并努力将该套接字与服务器结合起来。建立连接后,服务器在其通信端生成一个socket类的对象。客户端和服务器现在可以通过写入和读取套接字进行通信。

Java.net.Socket类描述了一个套接字, Java.net.ServerSocket类为服务器程序实现了一个工具,用于托管客户端并与它们建立连接。使用套接字编程在两个计算设备之间建立 TCP 连接的步骤



以下是使用套接字编程在两台计算机之间建立 TCP 连接的步骤如下:

步骤 1 –服务器实例化一个 ServerSocket 对象,指示将在哪个端口号通信。

步骤 2 –实例化 ServerSocket 对象后,服务器请求 ServerSocket 类的 accept() 方法。该程序暂停,直到客户端连接到给定端口上的服务器。

步骤 3 –服务器空闲后,客户端实例化 Socket 类的对象,定义要连接的服务器名称和端口号。

第四步——经过上面的步骤后,Socket类的构造函数努力将客户端连接到指定的服务器和端口号。如果通信得到验证,客户端立即拥有一个精通与服务器交互的 Socket 对象。

步骤 5 –在服务器端,accept() 方法返回对连接到客户端套接字的服务器上的新套接字的引用。

连接稳定后,可以使用 I/O 流进行通信。套接字类的每个对象都有一个 OutputStream 和一个 InputStream。客户端的OutputStream 与服务器的InputStream 相关联,客户端的InputStream 与服务器的OutputStream 结合。传输控制协议 (TCP) 是一种双向通信协议。因此,信息可以在相应的时间通过两个流传输。

套接字类 

Socket 类用于创建套接字对象,帮助用户实现所有基本的套接字操作。用户可以执行各种网络操作,例如发送、读取数据和关闭连接。使用Java.net.Socket类创建的每个 Socket 对象都专门与 1 个远程主机相关联。如果用户想要连接到另一台主机,那么他必须构建一个新的套接字对象。

Socket类的方法

在Socket编程中,客户端和服务端都有一个Socket对象,所以Socket类下的所有方法都可以被客户端和服务端调用。 Socket 类中有很多方法。



S No. 

Method

Description

1public void connect(SocketAddress host, int timeout)This method is used to connect the socket to the particularized host. This method is required only when the user instantiates the Socket applying the no-argument constructor.
2public int getPort()This method is used to return the port to which the socket is pinned on the remote machine.
3public InetAddress getInetAddress()This method is used to return the location of the other computer to which the socket is connected.
4public int getLocalPort()This method is used to return the port to which the socket is joined on the local machine.
5public SocketAddress getRemoteSocketAddress()  This method returns the location of the remote socket.
6public InputStream getInputStream()  This method is used to return the input stream of the socket. This input stream is combined with the output stream of the remote socket.
7public OutputStream getOutputStream()This method is used to return the output stream of the socket. The output stream is combined with the input stream of the remote socket.
8public void close() This method is used to close the socket, which causes the object of the Socket class to no longer be able to connect again to any server.

服务器套接字类

ServerSocket 类用于提供客户端/服务器套接字连接的服务器端的独立于系统的实现。如果 ServerSocket 类的构造函数无法侦听指定端口,则会引发异常。例如 - 如果端口已被使用,它将抛出异常。

ServerSocket 类的方法:

ServerSocket 类中有许多对用户非常有用的方法。这些方法是:

S no.

Method

Description

1public int getLocalPort()This method is used to return the port that the server socket is monitoring on. This method is beneficial if a user passed 0 as the port number in a constructor and lets the server find a port for him.
2public void setSoTimeout(int timeout)This method is used to set the time-out value for the time in which the server socket pauses for a client during the accept() method.
3public Socket accept()This method waits for an incoming client. This method is blocked till either a client combines to the server on the specified port or the socket times out, considering that the time-out value has been set using the setSoTimeout() method. Otherwise, this method will be blocked indefinitely.
4public void bind(SocketAddress host, int backlog) This method is used to bind the socket to the particularized server and port in the object of SocketAddress. The user should use this method if he has instantiated the ServerSocket using the no-argument constructor.

Java套接字编程示例:

下面的示例说明了一个非常基本的单向客户端和服务器设置,其中客户端连接,向服务器发送消息,服务器使用套接字连接显示它们。

客户端Java实现:

Java
// A Java program for a ClientSide
  
import java.io.*;
import java.net.*;
  
public class clientSide {
  
    // initialize socket and input output streams
    private Socket socket = null;
    private DataInputStream input = null;
    private DataOutputStream out = null;
  
    // constructor to put ip address and port
    public clientSide(String address, int port)
    {
  
        // establish a connection
        try {
  
            socket = new Socket(address, port);
  
            System.out.println("Connected");
  
            // takes input from terminal
            input = new DataInputStream(System.in);
  
            // sends output to the socket
            out = new DataOutputStream(
                socket.getOutputStream());
        }
  
        catch (UnknownHostException u) {
  
            System.out.println(u);
        }
  
        catch (IOException i) {
  
            System.out.println(i);
        }
  
        // string to read message from input
        String line = "";
  
        // keep reading until "End" is input
        while (!line.equals("End")) {
  
            try {
  
                line = input.readLine();
  
                out.writeUTF(line);
            }
  
            catch (IOException i) {
  
                System.out.println(i);
            }
        }
  
        // close the connection
        try {
  
            input.close();
  
            out.close();
  
            socket.close();
        }
  
        catch (IOException i) {
  
            System.out.println(i);
        }
    }
  
    public static void main(String[] args)
    {
  
        clientSide client
            = new clientSide("127.0.0.1", 5000);
    }
}


Java
// A Java program for a serverSide
import java.io.*;
import java.net.*;
  
public class serverSide {
  
    // initialize socket and input stream
    private Socket socket = null;
    private ServerSocket server = null;
    private DataInputStream in = null;
  
    // constructor with port
    public serverSide(int port)
    {
  
        // starts server and waits for a connection
        try {
            server = new ServerSocket(port);
  
            System.out.println("Server started");
  
            System.out.println("Waiting for a client ...");
  
            socket = server.accept();
  
            System.out.println("Client accepted");
  
            // takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(
                    socket.getInputStream()));
  
            String line = "";
  
            // reads message from client until "End" is sent
            while (!line.equals("End")) {
  
                try {
  
                    line = in.readUTF();
  
                    System.out.println(line);
                }
  
                catch (IOException i) {
  
                    System.out.println(i);
                }
            }
  
            System.out.println("Closing connection");
  
            // close connection
            socket.close();
  
            in.close();
        }
  
        catch (IOException i) {
  
            System.out.println(i);
        }
    }
  
    public static void main(String[] args)
    {
  
        serverSide server = new serverSide(5000);
    }
}


Java
import java.net.*;
  
public class InetAddressExample1 {
  
    public static void main(String[] args) throws UnknownHostException{
  
          
          // To get and print InetAddress of the Local Host
        InetAddress address = InetAddress.getLocalHost();
  
        System.out.println("InetAddress of the Local Host : "+address);
  
        // To get and print host name of the Local Host
        String hostName=address.getHostName();
  
        System.out.println("\nHost name of the Local Host : "+hostName);
  
    }
  
}


Java
import java.net.*;
  
public class InetAddressExample2 {
  
    public static void main(String[] args)
        throws UnknownHostException
    {
  
        // To get and print InetAddress of Named Hosts
        InetAddress address1 = InetAddress.getByName(
                           "write.geeksforgeeks.org");
  
        System.out.println("Inet Address of named hosts : "
                                               + address1);
  
        // To get and print ALL InetAddress of Named Host
        InetAddress arr[] = InetAddress.getAllByName(
                            "www.geeksforgeeks.org");
  
        System.out.println("\nInet Address of ALL named hosts :");
  
        for (int i = 0; i < arr.length; i++) {
  
            System.out.println(arr[i]);
        }
    }
}


Java
import java.net.*;
  
public class URLclassExample1 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        // creates a URL with string representation.
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // print the string representation of the URL
        String s = url.toString();
  
        System.out.println("URL :" + s);
    }
}


Java
import java.net.*;
  
public class URLclassExample2 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // to get and print the protocol of the URL
        String protocol = url.getProtocol();
  
        System.out.println("Protocol : " + protocol);
  
        // to get and print the hostName of the URL
        String host = url.getHost();
  
        System.out.println("HostName : " + host);
  
        // to get and print the file name of the URL
        String fileName = url.getFile();
  
        System.out.println("File Name : " + fileName);
    }
}


Java
import java.net.*;
  
public class URLclassExample3 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // to get and print the default port of the URL
        int defaultPort = url.getDefaultPort();
  
        System.out.println("Default Port : " + defaultPort);
  
        // to get and print the path of the URL
        String path = url.getPath();
  
        System.out.println("Path : " + path);
    }
}


服务器端Java实现:

Java

// A Java program for a serverSide
import java.io.*;
import java.net.*;
  
public class serverSide {
  
    // initialize socket and input stream
    private Socket socket = null;
    private ServerSocket server = null;
    private DataInputStream in = null;
  
    // constructor with port
    public serverSide(int port)
    {
  
        // starts server and waits for a connection
        try {
            server = new ServerSocket(port);
  
            System.out.println("Server started");
  
            System.out.println("Waiting for a client ...");
  
            socket = server.accept();
  
            System.out.println("Client accepted");
  
            // takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(
                    socket.getInputStream()));
  
            String line = "";
  
            // reads message from client until "End" is sent
            while (!line.equals("End")) {
  
                try {
  
                    line = in.readUTF();
  
                    System.out.println(line);
                }
  
                catch (IOException i) {
  
                    System.out.println(i);
                }
            }
  
            System.out.println("Closing connection");
  
            // close connection
            socket.close();
  
            in.close();
        }
  
        catch (IOException i) {
  
            System.out.println(i);
        }
    }
  
    public static void main(String[] args)
    {
  
        serverSide server = new serverSide(5000);
    }
}

在终端或命令提示符上运行

打开两个窗口,一个用于服务器,另一个用于客户端。

1.首先运行服务器应用程序。它会显示——

Server started
Waiting for a client …

2.然后在另一个终端上运行客户端应用程序。它会显示:

Connected 

服务器接受客户端并显示,

Client accepted

3.然后您可以开始在客户端窗口中输入消息。这是输出的示例视频。

网络地址

InetAddress 类用于提供获取任何主机名的 IP 地址的方法。 IP 地址由 32 位或 128 位无符号数表示。 InetAddress 的对象用其类似的主机名描述 IP 地址。 InetAddress 可以控制 IPv4 和 IPv6 地址。

有两种不同类型的地址:



  • 单播——它是单个接口的标识符。
  • 多播——它是接口集合的标识符。

InetAddress 类的方法

Java InetAddress 类表示 IP 地址。下面给出的是 InetAddress 类的重要方法——

S No.

Method

Description

1static InetAddress getByAddress(byte[] addr)This method is used to return an object of the InetAddress class provided the raw IP address.
2static InetAddress getByAddress(String host, byte[] addr)This method is used to create an InetAddress based on the given hostname and IP address.
3static InetAddress getByName(String host)This method is used to determine the IP address of a host when the host’s name is given.
4static InetAddress InetAddress getLocalHost()This method is used to return the localhost.
5String getHostName()This method is used to get the name of the IP address.
6String getHostAddress()This method returns the IP address in the form of a string in a textual display.
7String toString()This method is used to convert the IP address to a string.

Inet 地址类方法示例:

Java的实现 用于说明方法用法的Inet Address类如下所示:

示例 1:

Java

import java.net.*;
  
public class InetAddressExample1 {
  
    public static void main(String[] args) throws UnknownHostException{
  
          
          // To get and print InetAddress of the Local Host
        InetAddress address = InetAddress.getLocalHost();
  
        System.out.println("InetAddress of the Local Host : "+address);
  
        // To get and print host name of the Local Host
        String hostName=address.getHostName();
  
        System.out.println("\nHost name of the Local Host : "+hostName);
  
    }
  
}
输出
InetAddress of the Local Host : localhost/127.0.0.1

Host name of the Local Host : localhost

示例 2:

Java

import java.net.*;
  
public class InetAddressExample2 {
  
    public static void main(String[] args)
        throws UnknownHostException
    {
  
        // To get and print InetAddress of Named Hosts
        InetAddress address1 = InetAddress.getByName(
                           "write.geeksforgeeks.org");
  
        System.out.println("Inet Address of named hosts : "
                                               + address1);
  
        // To get and print ALL InetAddress of Named Host
        InetAddress arr[] = InetAddress.getAllByName(
                            "www.geeksforgeeks.org");
  
        System.out.println("\nInet Address of ALL named hosts :");
  
        for (int i = 0; i < arr.length; i++) {
  
            System.out.println(arr[i]);
        }
    }
}

输出



InetAddressExample2Output

网址类

Java的 URL 类是 Internet 上任何可用资源的入口点。类 URL 描述了统一资源定位符,它是万维网上“资源”的信号。源可以表示简单的文件或目录,也可以表示更困难的对象,例如对数据库或搜索引擎的查询。 URL 是字符串文本,可以识别 Internet 上的所有来源,向我们展示来源的地址、如何与之交互以及从中恢复某些内容。

网址类

URL 的组成部分

URL 可以有多种形式。然而,最一般的遵循三组件系统-

  1. 协议 – URL 中的协议定义了信息在主机和客户端(或 Web 浏览器)之间传输的方式。
  2. 主机名 –主机名是资源所在设备的名称。
  3. 文件名 -文件名是设备上文件的路径名。
  4. 端口号 –端口号用于唯一标识不同的应用程序。它通常是可选的。

Java URL 类的方法

Java URL 类中有很多Java网络中常用的方法。这些方法是:

S. No.MethodsDescription
1public String getProtocol()This method returns the protocol that is used by the URL.
2public String getHost()This method returns the hostname of the URL in IPv6 composition.
3public int getPort()This method returns the port associated with the protocol specified by the URL.
4public String getFile()This method returns the filename.
5public String getPath()This method returns the path of the URL, or null if empty.
6public String toString()This method is used to return the string representation of the provided URL object.
7public int getDefaultPort()This method returns the default port used.

URL 类方法示例

URL类的Java实现来说明方法的用法如下所示

示例 1:

Java

import java.net.*;
  
public class URLclassExample1 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        // creates a URL with string representation.
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // print the string representation of the URL
        String s = url.toString();
  
        System.out.println("URL :" + s);
    }
}
输出
URL :https://write.geeksforgeeks.org/post/3038131

示例 2:

Java

import java.net.*;
  
public class URLclassExample2 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // to get and print the protocol of the URL
        String protocol = url.getProtocol();
  
        System.out.println("Protocol : " + protocol);
  
        // to get and print the hostName of the URL
        String host = url.getHost();
  
        System.out.println("HostName : " + host);
  
        // to get and print the file name of the URL
        String fileName = url.getFile();
  
        System.out.println("File Name : " + fileName);
    }
}
输出
Protocol : https
HostName : write.geeksforgeeks.org
File Name : /post/3038131

示例 3:

Java

import java.net.*;
  
public class URLclassExample3 {
  
    public static void main(String[] args)
        throws MalformedURLException
    {
  
        URL url = new URL(
            "https://write.geeksforgeeks.org/post/3038131");
  
        // to get and print the default port of the URL
        int defaultPort = url.getDefaultPort();
  
        System.out.println("Default Port : " + defaultPort);
  
        // to get and print the path of the URL
        String path = url.getPath();
  
        System.out.println("Path : " + path);
    }
}
输出
Default Port : 443
Path : /post/3038131

这是对Java网络的简要介绍。在本文中,涵盖了Java网络简介、通用网络协议、 Java网络术语、 Java网络类、 Java网络接口、套接字编程、Inet 地址和 URL 类等许多重要主题。