Java 组播
MulticastSocketServer.java
1 package cn.edu.buaa.multicast; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.UnknownHostException; 8 9 /** 10 * One thing that we need to take into consideration here, is that there are 11 * specific addresses that allow us to use a MulticastSocket are limited, 12 * specifically in the range of 224.0.0.0 to 239.255.255.255. Some of them are 13 * reserved, like 224.0.0.0. The address that we are using, 224.0.0.3, can be 14 * used safely. 15 */ 16 public class MulticastSocketServer { 17 18 final static String INET_ADDR = "224.0.0.3"; 19 final static int PORT = 8888; 20 21 public static void main(String[] args) throws UnknownHostException, InterruptedException { 22 // Get the address that we are going to connect to. 23 InetAddress addr = InetAddress.getByName(INET_ADDR); 24 25 // Open a new DatagramSocket, which will be used to send the data. 26 try (DatagramSocket serverSocket = new DatagramSocket()) { 27 for (int i = 0; i < 5; i++) { 28 String msg = "Sent message no " + i; 29 30 // Create a packet that will contain the data 31 // (in the form of bytes) and send it. 32 DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, addr, PORT); 33 serverSocket.send(msgPacket); 34 35 System.out.println("Server sent packet with msg: " + msg); 36 Thread.sleep(500); 37 } 38 } catch (IOException ex) { 39 ex.printStackTrace(); 40 } 41 } 42 }
MulticastSocketClient.java
1 package cn.edu.buaa.multicast; 2 3 import java.io.IOException; 4 import java.net.DatagramPacket; 5 import java.net.InetAddress; 6 import java.net.MulticastSocket; 7 import java.net.UnknownHostException; 8 9 public class MulticastSocketClient { 10 final static String INET_ADDR = "224.0.0.3"; 11 final static int PORT = 8888; 12 13 public static void main(String[] args) throws UnknownHostException { 14 // Get the address that we are going to connect to. 15 InetAddress address = InetAddress.getByName(INET_ADDR); 16 17 // Create a buffer of bytes, which will be used to store 18 // the incoming bytes containing the information from the server. 19 // Since the message is small here, 256 bytes should be enough. 20 byte[] buf = new byte[256]; 21 22 // Create a new Multicast socket (that will allow other sockets/programs 23 // to join it as well. 24 try (MulticastSocket clientSocket = new MulticastSocket(PORT)) { 25 // Joint the Multicast group. 26 clientSocket.joinGroup(address); 27 28 while (true) { 29 // Receive the information and print it. 30 DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); 31 clientSocket.receive(msgPacket); 32 33 String msg = new String(buf, 0, buf.length); 34 System.out.println("Socket 1 received msg: " + msg); 35 } 36 } catch (IOException ex) { 37 ex.printStackTrace(); 38 } 39 } 40 }