-
使用数据报进行广播通信
DatagramSocket只允许数据报发往一个目的地址
MulticastSocket将数据报以广播方式发送到该端口的所有客户
MulticastSocket用在客户端,监听服务器广播来的数据
客户方程序:
public class MulticastClient {
public static void main(String[] args)throws IOException {
MulticastSocket socket = new MulticastSocket(4446);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
DatagramPacket packet;
//get a few quotes
for (int i=0;i<5;i++){
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("Quote of theMoment:"+received);
}
socket.leaveGroup(address);
socket.close();
}
}
服务器方程序:
public class MulticastServer {
public static void main(String[] args)throws java.io.IOException {
new MulticastServerThread().start();
}
}
程序MulticastServerThread
public class MulticastServerThread extends QuoteServerThread{
private long FIVE_SECOND=5000;
public MulticastServerThread()throws IOException {
super("MulticastServerThread");
}
public void run(){
while (moreQuotes){
try {
byte[] buf = new byte[256];
//construct quote
String dString = null;
if (in == null) dString = new Date().toString();
else dString = getNextQuote();
buf = dString.getBytes();
//send it
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
Socket.send(packet);
//sleep for a while
try {
sleep((long) (Math.random() * FIVE_SECOND));
} catch (InterruptedException e) {}
}catch(IOException e){
e.printStackTrace();
moreQuotes=false;
}
}
Socket.close();
}
}