//UdpReceive.java
/* 定義udp的接收端。 思路: 1.定義udpSocket服務。一般會監聽一個端口,事實上就是這個接收網絡應用程序定義一個數字標示。 2.定義一個數據包。用來存儲接收到的字節數據。 由於數據包對象中有特有功能能夠提取字節數據中不同數據信息。3.通過Socket服務的receive方法將收到的數據存入已定義好的數據包中。 4.通過數據包對象的特有功能將這些不同的數據取出。打印到控制台上。 5.關閉資源。
*/ import java.net.*; public class UdpReceive { public static void main(String[] args) throws Exception { //1.創建udp socket,建立端點。 DatagramSocket ds =new DatagramSocket(10000); //2.定義數據包。用於存儲數據。 byte[] buf = new byte[1024]; DatagramPacket dp =new DatagramPacket(buf,buf.length); //3.通過socket服務的receive方法將收到的數據存入數據包中。 ds.receive(dp); //4.通過數據包的方法獲取當中的數據。
String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(),0,dp.getLength()); int port = dp.getPort(); System.out.println(ip+":"+data+" port:"+port); //5.關閉資源。 ds.close(); } }
//UdpSend.java
/* 定義udp的發送端。 需求:通過udp傳輸方式。將一段文字數據發送出去。 思路: 1.建立UDPSocket服務。 2.提供數據。並將數據封裝到數據包中。 3.通過socket服務的發送功能,將數據包發出去。 4.關閉資源。 */ import java.net.*; public class UdpSend { public static void main(String[] args) throws Exception { //1.創建udp服務。通過DatagramSocket對象。 DatagramSocket ds = new DatagramSocket(8888); //2.確定數據。並封裝成數據包。 byte[] buf = " 網絡連通了!!!".getBytes();//將一個字符串轉化為一個字節數組 DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.111"),10000); //3.通過socket服務,將已有的數據包發送出去,通過send方法。 ds.send(dp); //4.關閉資源。 ds.close(); } }