知识背景:
组播使用UDP对一定范围内的地址发送相同的一组Packet,即一次可以向多个接受者发出信息,其与单播的主要区别是地址的形式。IP协议分配了一定范围的地址空间给多播(多播只能使用这个范围内的IP),IPv4中组播地址范围为224.0.0.0到239.255.255.255。
MulticastSocket概念:
java中通过MulticastSocket实例进行通信,使用时涉及到几个概念
①TTL(Time To Live),每个IP报文都包含一个TTL(是一个数字),报文每被一个路由转发一次它的TTL减1,当TTL变为0时,该报文被丢弃;
②多播组(multicast group),接受者只有加入这个组才能获取发送到该组的报文(这就确定了组播的对象);
代码实现:
1. 权限申请
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
2. 获取组播锁
调用MulticastLock对象的acquire方法,获取到组播锁,相应的,用完组播,为了不浪费电力,要调用MulticastLock的release方法释放锁
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
multicastLock = wifiManager.createMulticastLock("multicast.test");
multicastLock.acquire();
3. 释放组播锁
multicastLock.release();
4. 组播的初始化
private static final int PORT = 16664;
private static final String IP = "224.0.0.251";
MulticastSocket multicastSocket = new MulticastSocket(PORT);
InetAddress group = InetAddress.getByName(IP);
multicastSocket.setLoopbackMode(false);
multicastSocket.joinGroup(group);
5. 发送组播数据
String message = "hello" + index;
DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.length(), group, PORT);
try {
multicastSocket.send(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
index++;
6. 接收组播数据
byte[] buffer = new byte[1024 * 10];
DatagramPacket recv = new DatagramPacket(buffer, buffer.length, group, PORT);
while (true) {
try {
multicastSocket.receive(recv);
byte[] data = recv.getData();
} catch (IOException e) {
e.printStackTrace();
}
}
7. 组播的关闭
try {
multicastSocket.leaveGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
multicastSocket.close();
multicastSocket = null;
multicastLock.release();
结束...
来源:CSDN
作者:huangwenkui1990
链接:https://blog.csdn.net/huangwenkui1990/article/details/104049144