1.广播的发送
package com.softeem.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
/**
* 广播发送(基于UDP协议)
* @author LuFeng
*
*/
public class MulticastSocketDemo {
public static void main(String[] args) throws IOException {
String str="中国万岁";
//获取ip的对象
InetAddress it=InetAddress.getByName("228.5.6.7");
//获取多播数据报对象
MulticastSocket m=new MulticastSocket();
//将ip对象添加到多播数据报中
m.joinGroup(it);
byte[] b=str.getBytes();
//将要发送的消息打包
DatagramPacket dp=new DatagramPacket(b, 0, b.length, it, 8888);
//将消息发送出去
m.send(dp);
m.close();
}
}
2.广播的接收
package com.softeem.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
/**
* 广播接收(基于UDP协议)
* @author LuFeng
*
*/
public class MulticastSocketDemo1 {
public static void main(String[] args) throws IOException {
InetAddress it=InetAddress.getByName("228.5.6.7");
//通过8888端口进行广播的连接
MulticastSocket m=new MulticastSocket(8888);
//将ip地址添加到广播当中
m.joinGroup(it);
byte[] b=new byte[1024];
//将接收到的消息打包
DatagramPacket dp=new DatagramPacket(b, 0, b.length);
//接收消息
m.receive(dp);
//将数据解析成字符串
String str=new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
}
}