码迷,mamicode.com
首页 > 编程语言 > 详细

UDP 多播 Java

时间:2016-01-12 21:33:25      阅读:407      评论:0      收藏:0      [点我收藏+]

标签:

1、服务端

public class UdpMulticastServer {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        // 接受组播和发送组播的数据报服务都要把组播地址添加进来
        String host = "225.0.0.1";// 多播地址
        int port = 9998;
        int length = 1024;
        byte[] buf = new byte[length];
        MulticastSocket ms = null;
        DatagramPacket dp = null;
        try {
            ms = new MulticastSocket(port);
            dp = new DatagramPacket(buf, length);

            // 加入多播地址
            InetAddress group = InetAddress.getByName(host);
            ms.joinGroup(group);

            System.out.println("监听多播端口打开:");
            while (true) {
                ms.receive(dp);
                int i;
                StringBuffer sbuf = new StringBuffer();
                for (i = 0; i < 1024; i++) {
                    if (buf[i] == 0) {
                        break;
                    }
                    sbuf.append((char) buf[i]);
                }
                System.out.println("收到多播消息:" + sbuf.toString());
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、客户端

public class UdpMulticastClient {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // TODO Auto-generated method stub
        String host = "225.0.0.1";// 多播地址
        int port = 9998;
        String message = "test-multicastSocket";
        try {
            InetAddress group = InetAddress.getByName(host);
            MulticastSocket s = new MulticastSocket();
            // 加入多播组
            s.joinGroup(group);
            DatagramPacket dp = new DatagramPacket(message.getBytes(),
                    message.length(), group, port);
            while (true) {
                s.send(dp);
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

UDP 多播 Java

标签:

原文地址:http://www.cnblogs.com/diyishijian/p/5125557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!