UDP 核心特點
- 無連接、不可靠、無序、速度快
- 單個數據報 ≤ 64KB
- 適用場景:視頻流、即時通訊、廣播、允許丟包的高吞吐場景
核心類
DatagramSocket:發送/接收端點
DatagramPacket:數據報封裝(數據、長度、目標 IP/端口、源 IP/端口)
InetAddress:IP 地址封裝
完整代碼實現
package com.UDP.java;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.junit.Test;
public class TestUDP {
// 發送端
@Test
public void send() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(); // 隨機本地端口
byte[] data = "我是發送端".getBytes();
DatagramPacket packet = new DatagramPacket(
data, 0, data.length,
InetAddress.getByName("192.168.1.101"), 9090
);
ds.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) ds.close();
}
}
// 接收端
@Test
public void receive() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9090); // 綁定固定端口
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
ds.receive(packet); // 阻塞等待
String msg = new String(packet.getData(), 0, packet.getLength());
System.out.println("收到: " + msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) ds.close();
}
}
}
運行步驟
- 先運行
receive() 監聽 9090 端口
- 再運行
send() 發送數據
- 接收端控制台輸出:
收到: 我是發送端
關鍵點總結