Java网络编程深度解析:java.net包核心类与代码实例详解

2024-06-21 李腾 153 次阅读 0 次点赞
本文全面解析Java标准库中的java.net网络编程包,详细介绍了URL处理、TCP客户端-服务器通信、UDP数据报通信、IP地址操作等核心功能。通过完整的代码示例展示每个核心类的实际应用,包括URLConnection、Socket、ServerSocket、DatagramSocket和InetAddress的具体用法,帮助开发者快速掌握Java网络编程的关键技术和最佳实践。

java.net 包是 Java 标准库中用于网络编程的核心包,提供了实现网络应用程序的各种类和接口。

主要功能

1、URL 处理 - 用于处理统一资源定位符

2、TCP 通信 - 面向连接的可靠通信

3、UDP 通信 - 无连接的快速通信

4、IP 地址处理 - 网络地址的表示和解析

核心类

1、URL - 表示统一资源定位符

2、URLConnection - 建立与 URL 指向资源的连接

3、HttpURLConnection - 用于 HTTP 协议连接

4、Socket - 客户端 TCP 套接字

5、ServerSocket - 服务器端 TCP 套接字

6、DatagramSocket - UDP 套接字

7、InetAddress - IP 地址表示

示例代码

1. URL 处理示例

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

public class URLExample {
    public static void main(String[] args) {
        try {
            // 创建 URL 对象
            URL url = new URL("https://www.example.com");
            
            // 获取 URL 信息
            System.out.println("协议: " + url.getProtocol());
            System.out.println("主机: " + url.getHost());
            System.out.println("端口: " + url.getPort());
            System.out.println("路径: " + url.getPath());
            
            // 读取网页内容
            URLConnection connection = url.openConnection();
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
            
            String line;
            System.out.println("\n网页内容:");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. TCP 客户端-服务器通信

服务器端代码:

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

public class TCPServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("服务器启动,监听端口 8080...");
            
            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接: " + clientSocket.getInetAddress());
                
                // 处理客户端请求
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private static void handleClient(Socket clientSocket) {
        try (
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)
        ) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("收到消息: " + inputLine);
                
                // 回复客户端
                out.println("服务器回复: " + inputLine.toUpperCase());
                
                if ("bye".equalsIgnoreCase(inputLine)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客户端代码:

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

public class TCPClient {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8080;
        
        try (
            Socket socket = new Socket(hostname, port);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn = new BufferedReader(
                new InputStreamReader(System.in))
        ) {
            System.out.println("已连接到服务器 " + hostname + ":" + port);
            
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                // 发送消息到服务器
                out.println(userInput);
                
                // 接收服务器回复
                String response = in.readLine();
                System.out.println("服务器回复: " + response);
                
                if ("bye".equalsIgnoreCase(userInput)) {
                    break;
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("未知主机: " + hostname);
        } catch (IOException e) {
            System.err.println("I/O 错误: " + e.getMessage());
        }
    }
}

3. UDP 通信示例

UDP 服务器:

import java.net.*;

public class UDPServer {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(8888)) {
            System.out.println("UDP 服务器启动,端口 8888");
            
            byte[] buffer = new byte[1024];
            
            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                
                // 接收数据包
                socket.receive(packet);
                
                String received = new String(packet.getData(), 0, packet.getLength());
                System.out.println("收到来自 " + packet.getAddress() + ":" + 
                                 packet.getPort() + " 的消息: " + received);
                
                // 回复客户端
                String response = "UDP 服务器已收到: " + received;
                byte[] responseData = response.getBytes();
                
                DatagramPacket responsePacket = new DatagramPacket(
                    responseData, responseData.length, 
                    packet.getAddress(), packet.getPort());
                
                socket.send(responsePacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

UDP 客户端:

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

public class UDPClient {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket();
             BufferedReader stdIn = new BufferedReader(
                 new InputStreamReader(System.in))) {
            
            InetAddress serverAddress = InetAddress.getByName("localhost");
            
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                // 发送数据
                byte[] sendData = userInput.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(
                    sendData, sendData.length, serverAddress, 8888);
                socket.send(sendPacket);
                
                // 接收回复
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(
                    receiveData, receiveData.length);
                socket.receive(receivePacket);
                
                String response = new String(receivePacket.getData(), 0, 
                                           receivePacket.getLength());
                System.out.println("服务器回复: " + response);
                
                if ("bye".equalsIgnoreCase(userInput)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. InetAddress 使用示例

import java.net.*;

public class InetAddressExample {
    public static void main(String[] args) {
        try {
            // 获取本地主机信息
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println("本地主机: " + localHost);
            System.out.println("主机名: " + localHost.getHostName());
            System.out.println("IP地址: " + localHost.getHostAddress());
            
            System.out.println();
            
            // 通过主机名获取地址
            InetAddress googleAddress = InetAddress.getByName("www.google.com");
            System.out.println("Google IP: " + googleAddress.getHostAddress());
            
            System.out.println();
            
            // 获取所有地址
            InetAddress[] allAddresses = InetAddress.getAllByName("www.google.com");
            System.out.println("Google 的所有地址:");
            for (InetAddress addr : allAddresses) {
                System.out.println("  " + addr.getHostAddress());
            }
            
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

编译和运行

1、先启动服务器端程序

2、再运行客户端程序

3、在客户端输入消息与服务器通信

注意事项

1、网络操作需要处理 IOException

2、使用 try-with-resources 确保资源正确关闭

3、UDP 是无连接的,不保证数据包的顺序和可靠性

4、TCP 是面向连接的,保证数据的可靠传输

这些示例展示了 java.net 包的基本用法,可以根据具体需求进行扩展和修改。

最后更新于5月前
本文由人工编写,AI优化,转载请注明原文地址: Java网络编程完全指南:java.net包核心用法与实战代码示例

评论 (2)

登录 后发表评论

月光少女月光少女2025-11-16 19:07:04

非常实用的指南!示例代码很清晰,让我对java.net包的理解加深了。请问在处理UDP通信时,如何优化大数据包的传输性能?

小美不美小美不美2025-11-09 20:38:05

感谢作者分享这么详细的指南!示例代码很实用,帮我快速理解了Socket和ServerSocket的用法,正好用在了我的课程项目里。