(八)使用数据报进行广播通信

  • 使用数据报进行广播通信

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();
    }
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值