Socket本地组播Demo

本地组播窃听器

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

/**
 * 本地组播窃听器
 * @author Vic
 *
 */
public class MulticastSniffer {
	public static void main(String[] args) {
		InetAddress group = null;
		int port = 0;
		
		try{
			group = InetAddress.getByName("all-systems.mcast.net");
			port = 4000;
		}catch(Exception ex){
			System.err.println(ex);
			System.exit(1);
		}
		
		MulticastSocket ms = null ;
		try {
			ms = new MulticastSocket(port);
			ms.joinGroup(group);
			
			byte[] buffer = new byte[8192];
			while(true){
				DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
				ms.receive(dp);
				String s = new String(dp.getData());
				System.out.println(s);
			}
		} catch (IOException e) {
			System.err.println(e);
		}finally{
			if(ms != null){
				try {
					ms.leaveGroup(group);
					ms.close();
				} catch (IOException e) {
				}
			}
		}
	}
}



组播测试本地服务器发送10次数据

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

/**
 * 组播测试本地服务器发送10次数据
 * @author Vic
 *
 */
public class MulticastSender {
	public static void main(String[] args) {
		InetAddress ia = null;
		int port = 0 ;
		byte ttl = (byte) 1;
		
		try {
			ia = InetAddress.getByName("all-systems.mcast.net");
			port = 4000;
		} catch (UnknownHostException e) {
			System.err.println(e);
			System.exit(1);
		}
		
		byte[] data = "组播分发数据测试。。。。\r\n".getBytes();
		DatagramPacket dp = new DatagramPacket(data, data.length,ia,port);
		
		try {
			MulticastSocket ms = new MulticastSocket();
			ms.joinGroup(ia);
			for(int i=1;i<10;i++){
				ms.send(dp,ttl);
			}
			ms.leaveGroup(ia);
			ms.close();
		} catch(SocketException e){
			System.err.println(e);
		}catch (IOException e) {
			System.err.println(e);
		}
		
	}
}


 

你可能感兴趣的:(Socket本地组播Demo)