萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 網路安全 >  >> 網路基礎知識

Java網絡編程核心基石:三大要素、協議實現與Socket實戰代碼詳解

Java 憑藉強大的 `java.net` 包與跨平台特性,成為網絡編程首選語言。本文系統講解網絡通信三要素、核心 API、UDP/TCP 實戰模式、URL 處理、文件傳輸完整案例,助你快速掌握 Java 網絡開發精髓。

網絡通信三要素:連接的基因密碼

要素作用關鍵點
IP 地址主機唯一標識IPv4 32位/點分十進制;IPv6 128位/冒號十六進制;InetAddress 類封裝查詢/解析
端口號進程邏輯接口0-65535;0-1023 系統保留;`netstat -an` 查看佔用
通信協議通信規則契約UDP:無連接、不可靠、面向數據報、64KB 限制、低延遲(視頻/直播/DNS);TCP:面向連接、可靠、字節流、三次握手/四次揮手、流控/擁塞控制(文件/郵件/Web)

核心 API 深度解析

InetAddress:IP 地址封裝類

// 獲取本機
InetAddress local = InetAddress.getLocalHost();
// 域名解析
InetAddress baidu = InetAddress.getByName("www.baidu.com");
System.out.println(baidu.getHostAddress()); // IP
System.out.println(baidu.getHostName());    // 域名
// 批量解析
InetAddress[] arr = InetAddress.getAllByName("www.taobao.com");
// 可達性探測 (ICMP/ICMPv6)
boolean reachable = baidu.isReachable(3000); // 3s 超時

Socket 通用方法(TCP/UDP 通用基類)

  • `bind(SocketAddress)` / `connect(SocketAddress, timeout)`
  • `getInetAddress()` / `getPort()` / `getLocalAddress()` / `getLocalPort()`
  • `getInputStream()` / `getOutputStream()` 獲取字節流
  • `shutdownInput()` / `shutdownOutput()` 半關閉,`shutdownOutput()` 告知對端發送結束,觸發對端 `read()` 返回 -1。

UDP 編程:DatagramSocket + DatagramPacket

// 發送端
DatagramSocket ds = new DatagramSocket();
byte[] buf = "Hello UDP".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);
ds.close();

// 接收端 (持續監聽)
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
while (true) {
    DatagramPacket dp = new DatagramPacket(buf, buf.length);
    ds.receive(dp);
    String ip = dp.getAddress().getHostAddress();
    String data = new String(dp.getData(), 0, dp.getLength());
    int port = dp.getPort();
    System.out.printf("%s:%d -> %s%n", ip, port, data);
}

TCP 編程:ServerSocket + Socket

// 服務端
ServerSocket ss = new ServerSocket(10001);
while (true) {
    Socket s = ss.accept(); // 阻塞等待連接
    new Thread(() -> {
        try (InputStream in = s.getInputStream();
             OutputStream out = s.getOutputStream()) {
            // 讀取請求、處理業務、寫回響應
        } catch (IOException e) { e.printStackTrace(); }
    }).start();
}

// 客戶端
Socket s = new Socket("127.0.0.1", 10001);
OutputStream out = s.getOutputStream();
InputStream in = s.getInputStream();
// 發送請求、接收響應
s.shutdownOutput(); // 關鍵:告知服務端請求發送完畢

實戰案例:本地圖片上傳到服務器

客戶端

public class PicClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("117.84.140.104", 10001);
        try (FileInputStream fis = new FileInputStream("C:/Users/Admin/Desktop/1.jpg");
             OutputStream out = s.getOutputStream()) {
            byte[] buf = new byte[8192];
            int len;
            while ((len = fis.read(buf)) != -1) out.write(buf, 0, len);
        }
        s.shutdownOutput(); // 關鍵!
        try (InputStream in = s.getInputStream()) {
            byte[] buf = new byte[1024];
            int len = in.read(buf);
            System.out.println(new String(buf, 0, len)); // 打印 "上傳完畢"
        }
        s.close();
    }
}

服務端

public class PicServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(10001);
        Socket s = ss.accept();
        try (InputStream in = s.getInputStream();
             FileOutputStream fos = new FileOutputStream("C:/Users/Admin/Desktop/2.jpg");
             OutputStream out = s.getOutputStream()) {
            byte[] buf = new byte[8192];
            int len;
            while ((len = in.read(buf)) != -1) fos.write(buf, 0, len);
            out.write("上傳完畢".getBytes());
        }
        s.close();
        ss.close();
    }
}

URL 處理:資源定位與連接

  • `URL` 類:`getProtocol/Host/Port/Path/File/Query/Ref` 解析組件。
  • `openStream()` 直接獲取輸入流(簡單 GET)。
  • `URLConnection`:`openConnection()` → `setRequestProperty` 設置 Header → `connect()` 建立連接 → `getInputStream()` 讀響應 / `getOutputStream()` 發 POST 數據。支持 `HttpURLConnection` 專用方法(`setRequestMethod`、`setDoOutput`、`getResponseCode`)。

最佳實踐:生產環境優先使用成熟 HTTP 客戶端庫——OkHttp(連接池/攔截器/協議升級)、Apache HttpClient(豐富認證/重試/連接管理)、Spring WebClient/RestTemplate(響應式/聲明式),避免重複造輪子。

copyright © 萬盛學電腦網 all rights reserved