MulticastSocket 使用

/**
 * ServerMulticastSocketTest.java
 * 版权所有(C) 2014
 * 创建者:cuiran 2014-1-9 下午3:22:01
 */
package com.udpdemo.multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * TODO 
 * @author cuiran
 * @version 1.0.0
 */
public class ServerMulticastSocketTest {

	/**
	 * 2014-1-9 下午3:22:01
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MulticastSocket multicastSocket;
		try {
			multicastSocket = new MulticastSocket();
			InetAddress address = InetAddress.getByName("239.0.0.1"); // 必须使用D类地址
	        multicastSocket.joinGroup(address); // 以D类地址为标识,加入同一个组才能实现广播
	        
	        while (true) {
	            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	            byte[] buf = time.getBytes();
	            DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
	            datagramPacket.setAddress(address); // 接收地址和group的标识相同
	            datagramPacket.setPort(10000); // 发送至的端口号
	            
	            multicastSocket.send(datagramPacket);
	            Thread.sleep(1000);
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}

}
 
 
 
 
 
 

/**
 * ClientMulticastSocketTest.java
 * 版权所有(C) 2014
 * 创建者:cuiran 2014-1-9 下午3:24:25
 */
package com.udpdemo.multicast;

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

/**
 * TODO 
 * @author cuiran
 * @version 1.0.0
 */
public class ClientMulticastSocketTest {

	/**
	 * 2014-1-9 下午3:24:25
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MulticastSocket multicastSocket;
		try {
			multicastSocket = new MulticastSocket(10000);
			 InetAddress address = InetAddress.getByName("239.0.0.1");
		        multicastSocket.joinGroup(address);
		        byte[] buf = new byte[1024];
		        
		        while (true) {
		            DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length);
		            multicastSocket.receive(datagramPacket); // 接收数据,同样会进入阻塞状态
		            
		            byte[] message = new byte[datagramPacket.getLength()]; // 从buffer中截取收到的数据
		            System.arraycopy(buf, 0, message, 0, datagramPacket.getLength());
		            System.out.println(datagramPacket.getAddress());
		            System.out.println(new String(message));
		        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // 接收数据时需要指定监听的端口号
       
	}

}


你可能感兴趣的:(java,socket)