琥珀玲珑
琥珀玲珑的世界,也是你们的世界哦。大家一起来吧!!!!

IP多播地址采用D类IP地址, 地址范围是 224.0.0.0  239.255.255.255.

 

接收端:

package 组播套接字;

import java.io.*;
import java.net.*;

public class Client1 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
MulticastSocket ms=null;
InetAddress group=null;
try{
ms=new MulticastSocket(10000);
group=InetAddress.getByName("234.1.2.3");
ms.joinGroup(group);
byte[] buffer=new byte[8194];
System.out.println("接收数据包启动!(启动时间:)" + new java.util.Date() + ")");
while(true)
{
DatagramPacket dgp=new DatagramPacket(buffer,buffer.length);
ms.receive(dgp);
String s = new String(dgp.getData(), 0, dgp.getLength());
System.out.println(s);
}
}catch(IOException e)
{
e.printStackTrace();
}
//byte[] buffer2=new byte[dgp.getLength()];
//System.arraycopy(dgp.getData(), 0, buffer2, 0, dgp.getLength());
//System.out.println(new String(buffer2));
finally
{
if(ms!=null)
{
try{
ms.leaveGroup(group);
ms.close();
}catch(IOException e)
{

}
}
}
}

}

 

发送端:

package 组播套接字;

import java.io.IOException;
import java.net.*;

public class Server1 {

/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
int port=10000;
MulticastSocket ms=null;
InetAddress group=null;
System.out.println("服务器监听......\n");
try{
ms=new MulticastSocket();
group=InetAddress.getByName("234.1.2.3");
ms.joinGroup(group);
byte[] bb=new byte[8194];
System.out.println("发送数据包启动!(启动时间:)" + new java.util.Date() + ")");
while(true)
{
String message = "Hello------你好!!!!!" + new java.util.Date();
byte[] buffer = message.getBytes();
DatagramPacket dp=new DatagramPacket( buffer, buffer.length,group,port);
ms.send(dp);
//System.out.println("发送数据包给" + group + ":" + port);
Thread.sleep(5000);
}
}catch(IOException e)
{
e.printStackTrace();
}
finally{
if(ms!=null)
{
try{
ms.leaveGroup(group);
ms.close();
}
catch(IOException e)
{

}
}
}

}

}

 

posted on 2014-09-11 18:39  琥珀玲珑  阅读(106)  评论(0编辑  收藏  举报