简单的组播测试

public class Server extends Thread {

	private int PORT = 2012;// 发送组播信息的目标端口
	private String IP = "225.0.0.0";// 用于组播的IP

	public void sendMsg() throws IOException {
		while (true) {
			String msg = "这是组播发的消息!";
			byte[] date = msg.getBytes();
			// 创建组播地址对象
			InetAddress address = InetAddress.getByName(IP);
			// 数据包,将其发送到网关上
			java.net.DatagramPacket packet = new java.net.DatagramPacket(date,
					date.length, address, PORT);
			// 创建组播Socket,随机分配一个端口来进行组播信息的发送
			java.net.MulticastSocket socket = new java.net.MulticastSocket();
			try {
				// 发送组播的消息
				socket.send(packet);
				System.out.println("组播发的消息是:" + msg);
				Server.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String args[]) throws IOException {
		Server s = new Server();
		s.sendMsg();
	}
}

public class Client {
	private int PORT = 2012;// 接收组播信息的端口
	private String IP = "225.0.0.0";// 用于组播的IP

	public void reciveMsg() throws Exception {

		// 创建组播地址对象
		InetAddress address = InetAddress.getByName(IP);
		byte[] date = new byte[100];
		// 接收信息的数据包对象
		java.net.DatagramPacket packet = new java.net.DatagramPacket(date,
				date.length);
		// 创建组播Socket对象,在特定的端口上接收数据
		java.net.MulticastSocket socket = new java.net.MulticastSocket(PORT);
		// 加入到组中,才可以接收到消息
		socket.joinGroup(address);
		while (true) {
			socket.receive(packet);
			String s = (new String(date).trim() + "from" + packet.getAddress()
					+ ":" + packet.getPort());
			System.out.println("收到:" + s);
		}
	}

	public static void main(String args[]) throws Exception {
		Client c = new Client();
		c.reciveMsg();
	}
}

你可能感兴趣的:(java,C++,c,.net,socket)