Java Multicast多播实例程序 - 高飞网
59 人阅读

Java Multicast多播实例程序

2017-07-28 02:09:46

接收端:

package tcpip.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Receive {
    public static void main(String[] args) throws IOException {
        //1.准备好监听的端口和地址
        int port = 5000;// 监听端口
        String group = "239.4.5.6";// 监听ip组,范围是224.0.0.0 - 239.255.255.255
        //2.创建socket并绑定到指定端口
        MulticastSocket s = new MulticastSocket(port);
        //3.加入多播组
        s.joinGroup(InetAddress.getByName(group));
        // 到目前Socket已经建立了,接下来准备接收数据包
        //4.创建数据包,并准备接收
        byte buf[] = new byte[1024];
        DatagramPacket pack = new DatagramPacket(buf, buf.length);
        s.receive(pack);
        //5.打印下数据包的相关信息
        System.out.println("Receive data from :" + pack.getAddress().toString() + //
                ":" + pack.getPort() + " with length:" + //
                pack.getLength());
        System.out.println();
        //6.完成数据包接收之后,离开多播组,关闭socket
        s.leaveGroup(InetAddress.getByName(group));
        s.close();
        

    }
}


发送端:

package tcpip.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class Send {
    public static void main(String[] args) throws IOException {
        //1.准备好目的地址和端口
        int port = 5000;// 监听端口
        String group = "239.4.5.6";// 监听ip组,范围是224.0.0.0 - 239.255.255.255
        int newttl = 1;
        //2.创建socket,但不绑定端口,因为我们只需发送数据
        MulticastSocket s = new MulticastSocket();
        //3.不必加入多播组,因为只发送数据
        //4.
        byte buf[] = new byte[10];
        for(int i=0;i<buf.length;i++){
            buf[i]=(byte)i;
        }
        //创建数据包
        DatagramPacket pack = new DatagramPacket(buf, buf.length,InetAddress.getByName(group),port);
        //
        int ttl = s.getTimeToLive();
        s.setTimeToLive(newttl);
        s.send(pack);
        s.setTimeToLive(ttl);
        s.close();
    }
}


参考:

java multicast_example


还没有评论!
54.156.93.60