1. 组播知识介绍: http://blog.csdn.net/happy_david/article/details/1569209
2. java 组播实现:来自: http://blog.csdn.net/a352193394/article/details/7395600
下面来演示一下使用Java Socket的组播类实现一个组播的小案例
首先是接收端
- package com.bird.test;
- import java.net.DatagramPacket;
- import java.net.InetAddress;
- import java.net.MulticastSocket;
- import java.util.Date;
- /**
- * 组播的客户端
- * @author Bird
- *
- */
- public class MulticastReceive {
- public static void main(String[] args) throws Exception {
- test();
- }
- public static void test() throws Exception{
- InetAddress group = InetAddress.getByName("224.0.0.2");//组播地址
- int port = 8888;
- MulticastSocket msr = null;//创建组播套接字
- try {
- msr = new MulticastSocket(port);
- msr.joinGroup(group);//加入连接
- byte[] buffer = new byte[8192];
- System.out.println("接收数据包启动!(启动时间: "+new Date()+")");
- while(true){
- //建立一个指定缓冲区大小的数据包
- DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
- msr.receive(dp);
- String s = new String(dp.getData(),0,dp.getLength());
- //解码组播数据包
- System.out.println(s);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- if(msr!=null){
- try {
- msr.leaveGroup(group);
- msr.close();
- } catch (Exception e2) {
- // TODO: handle exception
- }
- }
- }
- }
- }
然后是发送端
- package com.bird.test;
- import java.net.DatagramPacket;
- import java.net.InetAddress;
- import java.net.MulticastSocket;
- import java.util.Date;
- /**
- * 组播的服务端
- * @author Bird
- *
- */
- public class MulticastSender {
- public static void server() throws Exception{
- InetAddress group = InetAddress.getByName("224.0.0.2");//组播地址
- int port = 8888;
- MulticastSocket mss = null;
- try {
- mss = new MulticastSocket(port);
- mss.joinGroup(group);
- System.out.println("发送数据包启动!(启动时间"+new Date()+")");
- while(true){
- String message = "Hello "+new Date();
- byte[] buffer = message.getBytes();
- DatagramPacket dp = new DatagramPacket(buffer, buffer.length,group,port);
- mss.send(dp);
- System.out.println("发送数据包给 "+group+":"+port);
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- try {
- if(mss!=null){
- mss.leaveGroup(group);
- mss.close();
- }
- } catch (Exception e2) {
- // TODO: handle exception
- }
- }
- }
- public static void main(String[] args) throws Exception {
- server();
- }
- }
通过开启多个接收端,然后开启发送端,就可以实现组播的效果
!#Never too late to do it now#!