使用UDP协议编写一个网络程序,设置接收端程序的监听端口是8001,发送端发送的数据是“Hello, world‘’.
接收端:
1 import java.net.*; 2 public class example { 3 4 public static void main(String[] args) throws Exception 5 { 6 byte[] buf=new byte[1024]; 7 DatagramSocket ds=new DatagramSocket(8001); 8 DatagramPacket dp=new DatagramPacket(buf,1024); 9 System.out.println("等待接受数据"); 10 ds.receive(dp); 11 String str=new String(dp.getData()); 12 System.out.println(str); 13 ds.close(); 14 } 15 16 }
发送端:
1 import java.net.*; 2 public class example1 { 3 4 public static void main(String[] args) throws Exception{ 5 DatagramSocket ds=new DatagramSocket(3000); 6 String str="Hello, world"; 7 DatagramPacket dp=new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),8001); 8 System.out.println("发送消息"); 9 ds.send(dp); 10 ds.close(); 11 } 12 }
运行结果: