| package com.socket.demo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceiveDemo2 { public static void main(String[] args) throws IOException{ System.out.println("接收端啟動…………"); /* 2、建立UDP的socket的服務,必須明確一個連接埠號碼 3、建立資料包,用於儲存接收到的資料,方便用資料包對象的方法解析這些資料 4、使用DatagramSocket的receive方法將接收到的資料存放區到資料包中 5、通過資料包的方法解析資料包中的資料 5、關閉socket服務 */ //udpsocket服務,使用DatagramSocket對象 DatagramSocket ds=new DatagramSocket(10003); while(true){ //使用DatagramPacket將資料封裝到該對象中 byte[] buf=new byte[1024]; DatagramPacket dp=new DatagramPacket(buf, buf.length); //通過udp的socket服務將資料包發送出去,通過send方法 ds.receive(dp);//阻塞式的。 //通過資料包的方法解析資料包中的資料,比如,地址、連接埠、資料內容等 String ip=dp.getAddress().getHostAddress(); //String name=dp.getAddress().getHostName(); int port=dp.getPort(); String text=new String(dp.getData(),0,dp.getLength()); //System.out.println("-----"+ip+"-----"+name+"-----"+port+"-----"+text); System.out.println("-----"+ip+"----------"+port+"-----"+text); } //關閉資源 //ds.close(); } } |