Java实现UDP组播(支持跨网段)

以下是接收端代码:

package com.udp.test;

import sun.security.util.BitArray;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;

/**
 * @Author lenovo
 * @Date 2019/7/18
 * @Time 15:57
 */
public class MyUdp {

    /**
     * 端口
     */
    private static int port=12501;

    /**
     * 接收字节组播
     */
    private static byte[] receiveBytes=new byte[1024];
    /**
     * 组播地址
     */
    private static InetAddress address=null;

    /**
     * 套解字
     */
    private static MulticastSocket multicastSocket=null;
    /**
     * 用户数据报
     */
    private static DatagramPacket datagramPacket=null;
    public static void main(String[] args){
        try {
            multicastSocket=new MulticastSocket(port);
            multicastSocket.setTimeToLive(254);
            address=InetAddress.getByName("232.10.8.7");
            multicastSocket.joinGroup(address);
            datagramPacket=new DatagramPacket(receiveBytes,0,1024,address,port);
            receiveBytes();
            System.in.read();
        }catch (java.io.IOException ex){

        }
    }

    /**
     * 接收数据
     */
    private static void receiveBytes(){
        try {
            multicastSocket.receive(datagramPacket);
            byte[] data=datagramPacket.getData();
            byte[] validBytes=new byte[datagramPacket.getLength()];
            System.arraycopy(data,0,validBytes,0,validBytes.length);
            String message=DatatypeConverter.printHexBinary(validBytes);
            InetSocketAddress address=(InetSocketAddress)datagramPacket.getSocketAddress();
            System.out.println("来自【"+address.toString()+"】的消息:"+message);
            receiveBytes();
        }catch (IOException e){

        }
    }
}

发送端是C#写的,这里就不贴出来了。

测试结果:

Java实现UDP组播(支持跨网段)_第1张图片

你可能感兴趣的:(Java)