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

UDP 广播 Java

时间:2016-01-12 21:27:03      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

1、服务端

public class UdpBroadcastServer {

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

        // TODO Auto-generated method stub
        int port = 9999;// 开启监听的端口
        DatagramSocket ds = null;
        DatagramPacket dp = null;
        byte[] buf = new byte[1024];// 存储发来的消息
        try {
            // 绑定端口的
            ds = new DatagramSocket(port);
            dp = new DatagramPacket(buf, buf.length);
            System.out.println("监听广播端口打开:");
            while (true) {
                ds.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 (SocketException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2、客户端

public class UdpBroadcastClient {

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

        // TODO Auto-generated method stub
        // 广播的实现 :由客户端发出广播,服务器端接收
        String host = "255.255.255.255";// 广播地址
        int port = 9999;// 广播的目的端口
        String message = "test";// 用于发送的字符串
        try {
            InetAddress adds = InetAddress.getByName(host);
            DatagramSocket ds = new DatagramSocket();
            DatagramPacket dp = new DatagramPacket(message.getBytes(),
                    message.length(), adds, port);
            while (true) {
                ds.send(dp);
                try {
                    Thread.sleep(1000);
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (SocketException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

UDP 广播 Java

标签:

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

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