UDP 是User Datagram Protocol的簡稱,一種無連接的傳輸層協議,提供面向事務的簡單不可靠信息傳送服務。
發送端分析:
1.創建發送端Socket對象
2.創建數據並打包
3.發送數據
接收端分析:
1.創建接收端Socket對象
2.接收數據
3.解析數據
4.將接收到的數據打印到控制台
發送端代碼:
public class UDPSendTest { public static void main(String[] args) throws Exception { //創建發送端Socket對象 DatagramSocket ds = new DatagramSocket(); //創建數據並打包 String s = "My name is happywindman"; byte[] bytes = s.getBytes(); int length = s.length(); InetAddress ip = InetAddress.getByName("192.168.3.100");//根據自己主機的ip地址或者主機名 int port = 10086; DatagramPacket dp = new DatagramPacket(bytes,length,ip,port); //發送數據 ds.send(dp); //釋放資源 ds.close(); } }
接收端代碼:
public class UDPReceiveTest { public static void main(String[] args) throws Exception { //創建接收端Socket對象 DatagramSocket ds = new DatagramSocket(10086); //接收數據 byte[] bytes = new byte[1024]; int length = bytes.length; DatagramPacket dp = new DatagramPacket(bytes, length); ds.receive(dp); //解析數據 InetAddress address = dp.getAddress(); byte[] data = dp.getData(); int len = dp.getLength(); //輸出數據 System.out.println(address); System.out.println(new String(data,0,len)); } }
先運行接收端代碼,然后再運行發送端代碼就可以看到發送的數據被打印到控制台了