欢迎访问宙启技术站
智能推送

Java网络函数:网络编程中的常用函数及其用法

发布时间:2023-06-18 17:07:02

Java是目前应用最广泛的编程语言之一,它的网络编程功能也非常强大。在网络编程中,Java提供了一系列的网络函数,用于实现网络通信的各种功能。下面我们来介绍一些常用的Java网络函数及其用法。

1. InetAddress类

InetAddress类是表示IP地址的类,它提供了一些方法用于获取主机名和IP地址,如getHostName()和getHostAddress()方法。

示例代码:

import java.net.*;

public class InetAddressDemo {

    public static void main(String[] args) {

        try {
            //获取本机的IP地址和主机名
            InetAddress inetAddress = InetAddress.getLocalHost();
            System.out.println("本机IP地址:" + inetAddress.getHostAddress());
            System.out.println("本机主机名:" + inetAddress.getHostName());

            //获取百度的IP地址和主机名
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println("百度IP地址:" + inetAddress2.getHostAddress());
            System.out.println("百度主机名:" + inetAddress2.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

2. Socket类

Socket类是实现套接字通信的基本类,它提供了一些方法用于创建、连接和关闭套接字,以及发送和接收数据。下面是一个简单的Java Socket服务器和客户端的示例代码:

Server端代码:

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

public class Server {
    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务器已启动,等待客户端连接...");

            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接...");

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = in.readLine();
            System.out.println("客户端消息:" + line);

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("服务端已收到消息:" + line);

            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client端代码:

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

public class Client {
    public static void main(String[] args) {

        try {
            Socket socket = new Socket("localhost", 8888);

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println("你好,服务端!");

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = in.readLine();
            System.out.println("服务端返回消息:" + line);

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. URL类

URL类是用于在网上定位资源的类,它提供了一些方法用于获取URL的各种信息,如协议、主机名、端口号、路径、文件名等。

示例代码:

import java.net.*;

public class URLDemo {
    public static void main(String[] args) {

        try {
            URL url = new URL("http://www.baidu.com");
            System.out.println("协议:" + url.getProtocol());
            System.out.println("主机名:" + url.getHost());
            System.out.println("端口号:" + url.getPort());
            System.out.println("路径:" + url.getPath());
            System.out.println("文件名:" + url.getFile());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

4. HttpURLConnection类

HttpURLConnection类是基于HTTP协议的连接类,它提供了一些方法用于发送HTTP请求和接收HTTP响应。可以使用它来实现HTTP客户端的功能。

示例代码:

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

public class HttpClient {
    public static void main(String[] args) {

        try {
            URL url = new URL("http://www.baidu.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }

            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. DatagramPacket类和DatagramSocket类

DatagramPacket类和DatagramSocket类是实现基于UDP协议的数据报通信的类。DatagramPacket类表示一个UDP数据包,它包括数据和目的地址等信息;DatagramSocket类表示一个UDP套接字,它提供了一些方法用于发送和接收UDP数据包。

示例代码:

Server端代码:

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

public class UDPServer {
    public static void main(String[] args) {

        try {
            DatagramSocket serverSocket = new DatagramSocket(8888);
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            System.out.println("服务器已启动,等待客户端连接...");
            serverSocket.receive(packet);
            System.out.println("客户端已连接:" + packet.getAddress().getHostAddress());

            String message = new String(packet.getData(), 0, packet.getLength());
            System.out.println("客户端消息:" + message);

            byte[] data = "服务端已收到客户端消息".getBytes();
            DatagramPacket packet1 = new DatagramPacket(data, data.length, packet.getAddress(), packet.getPort());
            serverSocket.send(packet1);

            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client端代码:

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

public class UDPClient {
    public static void main(String[] args) {

        try {
            DatagramSocket socket = new DatagramSocket();
            byte[] data = "你好,服务端!".getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getLocalHost(), 8888);

            socket.send(packet);

            byte[] buffer = new byte[1024];
            DatagramPacket packet1 = new DatagramPacket(buffer, buffer.length);

            socket.receive(packet1);
            System.out.println("服务端返回消息:" + new String(packet1.getData(), 0, packet1.getLength()));

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上就是Java网络编程中常用的一些函数及其用法。在实际开发中,我们可以根据需要灵活运用这些函数来实现各种网络通信的功能。