網路程式設計--使用UDP傳送接收資料
阿新 • • 發佈:2018-12-16
package com.zhangxueliang.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * 使用UDP協議傳送接收資料 * @author zxlt * */ public class SendDemo { public static void main(String[] args) throws IOException { //建立傳送端socket物件DatagramSocket ds = new DatagramSocket(); //建立資料並打包 String s = "Hello udp222,Im coming"; byte[] bys = s.getBytes(); int length = bys.length; InetAddress address = InetAddress.getByName("zxlt"); int port = 8888; //打包 DatagramPacket dp = newDatagramPacket(bys,length,address,port); //傳送資料 ds.send(dp); //釋放資源 ds.close(); } }
package com.zhangxueliang.udp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class ReceiveDemo {public static void main(String[] args) throws IOException { //建立接收端Socket物件 DatagramSocket ds = new DatagramSocket(8888); //接收資料 byte[] bys = new byte[1024]; DatagramPacket dp = new DatagramPacket(bys,bys.length); System.out.println(1); ds.receive(dp);//阻塞 System.out.println(2); //解析資料 InetAddress address = dp.getAddress(); byte[] data = dp.getData(); int length = dp.getLength(); //輸出資料 System.out.println("sender--> "+address.getHostAddress()); System.out.println(new String(bys,0,length)); //釋放資源 ds.close(); } }