UDP通信(多播)(java)

java中实现udp通信非常简单,只需要创建DatagramSocket,然后使用DatagramSocket发送DatagramPacket即可。

接收端

30012为接收端的端口号

    public static void main(String[] args) {
        try {
            DatagramSocket dgSocket = new DatagramSocket(30012);
            byte[] by = new byte[1024];
            DatagramPacket packet=new DatagramPacket(by,by.length);
            while ( ! Thread.currentThread().isInterrupted()){
                try {
                    dgSocket.receive(packet);
                    String str=new String(packet.getData(),0,packet.getLength());
                    System.out.println("接收到消息:"+str);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            dgSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

发送端

192.168.1.103为接收端的主机ip地址,30012为接收端的端口号
这里也可以将ip设置为广播地址,这样局域网内所有的主机都会接收到该数据包

public static void main(String[] args) {
        try {
            DatagramSocket dgSocket = new DatagramSocket();
            String msg = "你好,这是我发给你的消息";
            DatagramPacket dgPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length,
                    InetAddress.getByName("192.168.1.103"),30012);
            while ( ! Thread.currentThread().isInterrupted()){
                dgSocket.send(dgPacket);
                System.out.println("发送消息:"+msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            dgSocket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)