一、UDP协议无状态协议,不可靠协议,单向通信,数据包
广播方:
1 import java.io.IOException; 2 import java.net.DatagramPacket; 3 import java.net.DatagramSocket; 4 import java.net.InetAddress; 5 import java.sql.SQLException; 6 7 public class Broadcast { 8 9 public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException { 10 DatagramSocket ds=new DatagramSocket(); 11 InetAddress address=InetAddress.getByName("123.123.123.123");//输入本服务器IP 12 byte [] bs="广播一条通知:".getBytes(); 13 DatagramPacket dp=new DatagramPacket(bs, bs.length,address,6666);//端口号自定义 14 ds.send(dp); 15 ds.close(); 16 } 17 }
听众方:
1 import java.io.IOException; 2 import java.net.DatagramPacket; 3 import java.net.DatagramSocket; 4 import java.net.InetAddress; 5 import java.sql.SQLException; 6 public class UDPClient { 7 8 public static void main(String[] args) throws IOException{ 9 DatagramSocket ds=new DatagramSocket(6666); 10 byte[] bs=new byte[65536]; 11 DatagramPacket dp=new DatagramPacket(bs, bs.length); 12 ds.receive(dp); 13 String s=new String(dp.getData()); 14 System.out.println("收到的数据为:"+s.substring(0,dp.getLength()/2)+";收到的位移偏量为:"+dp.getOffset()+";有效长度为:"+dp.getLength()); 15 16 } 17 }