IP多点广播原理
设置一组特殊网络地址作为多点广播地址,每一个多点广播地址都被看作一个组,当客户需要发送和接受信息时,加入到该组即可。
IP协议为多点广播提供了一批特殊的IP地址,范围是224.0.0.0 ~ 239.255.255.255
JAVA中使用MutilcastSocket加入一个广播组(joinGroup),从而在组内发送和接受数据报DatagramPacket。
MutilcastSocket比起普通的UDP通信的DatagramSocket多了setTimeToLive(int ttl),参数ttl决定广播组的范围,默认为1,表示局域网。
下面是一个简单例子,BroadcastSocket中用一个线程接收键盘输入(因为会阻塞)并使用MutilcastSocket发送数据,
用另一个线程从MutilcastSocket读取数据并打印出来,
1 package udp; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.InetAddress; 6 import java.net.MulticastSocket; 7 import java.util.Scanner; 8 9 public class BroadcastSocket implements Runnable{ 10 private static final String BROADCAST_IP = "230.0.0.1"; 11 public static final int BROADCAST_PORT = 3000; 12 private static final int DATA_LEN = 4096; 13 private MulticastSocket socket = null; 14 private InetAddress broadcastAddress = null; 15 //用来接收键盘输入 16 private Scanner scan = null; 17 //用来接收网络字节 18 byte[] inBuff = new byte[DATA_LEN]; 19 //用将inBuff封装进DatagramPacket 20 private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length); 21 //封装发送数据的DatagramPacket 22 private DatagramPacket outPacket = null; 23 public void init() throws IOException { 24 try { 25 Scanner scan = new Scanner(System.in); 26 socket = new MulticastSocket(BROADCAST_PORT); 27 broadcastAddress = InetAddress.getByName(BROADCAST_IP); 28 socket.joinGroup(broadcastAddress); 29 //设置本是否阻止MulticastSocket会发送给自身, true表示阻止 30 socket.setLoopbackMode(false); 31 //初始化outPacket 32 outPacket = new DatagramPacket(new byte[0], 0 , broadcastAddress, BROADCAST_PORT); 33 new Thread(this).start(); 34 //读取键盘输入 35 while (scan.hasNextLine()) { 36 //需要先将键盘输入转为byte字节才能设置DatagramPacket的值 37 byte[] buff = scan.nextLine().getBytes(); 38 outPacket.setData(buff); 39 socket.send(outPacket); 40 } 41 } finally { 42 socket.close(); 43 } 44 } 45 @Override 46 public void run() { 47 try { 48 while (true) { 49 socket.receive(inPacket); 50 System.out.println("聊天信息:"+new String(inBuff, 0, inPacket.getLength())); 51 } 52 } //捕获异常 53 catch (IOException ex) { 54 ex.printStackTrace(); 55 try { 56 if (socket != null) { 57 socket.leaveGroup(broadcastAddress); 58 socket.close(); 59 } 60 System.exit(1); 61 } catch (IOException e) { 62 e.printStackTrace(); 63 } 64 } 65 66 } 67 68 public static void main(String[] args) throws IOException { 69 new BroadcastSocket().init(); 70 } 71 }
执行结果如下,