Java Socket编程(四)Socket进阶


一、多播与广播

我们可以向每个接受者单播一个数据副本,但这样做效率可能非常低。
只有UDP套接字允许广播和多播,两者的区别是:广播会发送到网络上所有可达的
主机,有些操作系统可能不允许普通用户进行广播操作;而多播只发送给感兴趣的
主机。具体来说是调用MulticastSocket的joinGroup()加入到多播组的主机。

public class MulticastReceiverTest {

	public static void main(String[] args) throws Exception {
		
		final InetAddress address = InetAddress.getByName("224.1.1.1");
		final int port = 45599;

		for (int i = 0; i < 5; i++) {
			new Thread("Thread #" + i){
				@Override
				public void run() {
					try {
						MulticastSocket sock = new MulticastSocket(port);
						sock.joinGroup(address);
						
						byte[] msg = new byte[256];
						DatagramPacket packet = new DatagramPacket(msg, msg.length);
						
						sock.receive(packet);
						System.out.println(Thread.currentThread().getName() + 
								" receive: " + new String(packet.getData()));
					} 
					catch (IOException e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
		
		Thread.sleep(2000);
		
		MulticastSocket sock = new MulticastSocket();
		sock.setTimeToLive(32);
		
		byte[] msg = "hellomulticast".getBytes();
		DatagramPacket packet = new DatagramPacket(msg, msg.length, address, port);
		
		sock.send(packet);
		System.out.println("Message sent");
	}

}

你可能感兴趣的:(java,thread,编程,exception,socket,byte)