JAVA基础知识之网络编程——-使用MutilcastSocket实现多点广播

时间:2023-08-07 11:25:02
JAVA基础知识之网络编程——-使用MutilcastSocket实现多点广播

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读取数据并打印出来,

 package udp;

 import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Scanner; public class BroadcastSocket implements Runnable{
private static final String BROADCAST_IP = "230.0.0.1";
public static final int BROADCAST_PORT = 3000;
private static final int DATA_LEN = 4096;
private MulticastSocket socket = null;
private InetAddress broadcastAddress = null;
//用来接收键盘输入
private Scanner scan = null;
//用来接收网络字节
byte[] inBuff = new byte[DATA_LEN];
//用将inBuff封装进DatagramPacket
private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
//封装发送数据的DatagramPacket
private DatagramPacket outPacket = null;
public void init() throws IOException {
try {
Scanner scan = new Scanner(System.in);
socket = new MulticastSocket(BROADCAST_PORT);
broadcastAddress = InetAddress.getByName(BROADCAST_IP);
socket.joinGroup(broadcastAddress);
//设置本是否阻止MulticastSocket会发送给自身, true表示阻止
socket.setLoopbackMode(false);
//初始化outPacket
outPacket = new DatagramPacket(new byte[0], 0 , broadcastAddress, BROADCAST_PORT);
new Thread(this).start();
//读取键盘输入
while (scan.hasNextLine()) {
//需要先将键盘输入转为byte字节才能设置DatagramPacket的值
byte[] buff = scan.nextLine().getBytes();
outPacket.setData(buff);
socket.send(outPacket);
}
} finally {
socket.close();
}
}
@Override
public void run() {
try {
while (true) {
socket.receive(inPacket);
System.out.println("聊天信息:"+new String(inBuff, 0, inPacket.getLength()));
}
} //捕获异常
catch (IOException ex) {
ex.printStackTrace();
try {
if (socket != null) {
socket.leaveGroup(broadcastAddress);
socket.close();
}
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
}
} } public static void main(String[] args) throws IOException {
new BroadcastSocket().init();
}
}

执行结果如下,

JAVA基础知识之网络编程——-使用MutilcastSocket实现多点广播