1
2
3
4
5 package org.neo.swarm.util.network.multicast;
6 import java.io.IOException;
7 import java.net.DatagramPacket;
8 import java.net.InetAddress;
9 import java.net.MulticastSocket;
10 import java.net.UnknownHostException;
11 /***
12 * Receives multicast byte[] data.
13 * @author navery
14 */
15 public class MulticastReader implements Receiver {
16 MulticastSocket socket;
17 int port;
18 String address;
19 int packetSize = 16 * 1024;
20 private byte[] buffer;
21
22 /***
23 *
24 * @param timeout specifies blocking operation timeout in ms. 0 is infinite
25 */
26 public MulticastReader(InetAddress group, int port, int timeout) {
27 try {
28 buffer = new byte[packetSize];
29 this.port = port;
30 socket = new MulticastSocket(port);
31 socket.joinGroup(group);
32 socket.setSoTimeout(timeout);
33 } catch (IOException ex) {
34 System.out.println("Multicast startup failed, Check your network is connected...");
35 ex.printStackTrace();
36 }
37 }
38
39
40
41
42 public byte[] read() throws IOException {
43 DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
44 socket.receive(packet);
45 return packet.getData();
46 }
47
48
49
50 public void close() throws IOException {
51 try {
52 socket.leaveGroup(InetAddress.getByName(address));
53 } catch (UnknownHostException e) {
54 e.printStackTrace();
55 }
56 socket.close();
57 }
58 }