1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package net.sf.sail.common.messaging.multicast;
24
25 import java.util.logging.Logger;
26
27 import java.io.IOException;
28 import java.net.DatagramPacket;
29 import java.net.InetAddress;
30 import java.net.MulticastSocket;
31 import java.util.HashSet;
32 import java.util.Set;
33
34
35
36
37 public class MulticastReceiverThread extends Thread {
38
39
40
41 private static final Logger logger = Logger
42 .getLogger(MulticastReceiverThread.class.getName());
43
44 InetAddress address;
45
46 Set<MessageListener> listeners = new HashSet<MessageListener>();
47
48 DatagramPacket packet;
49
50 MulticastSocket socket;
51
52 public MulticastReceiverThread() throws IOException {
53 socket = new MulticastSocket(Multicaster.SAIL_PORT);
54 address = InetAddress.getByName("230.0.0.1");
55 socket.joinGroup(address);
56 }
57
58
59
60
61 public void addMessageListener(MessageListener listener) {
62 listeners.add(listener);
63 }
64
65 @Override
66 public void run() {
67 while (true) {
68 byte[] buf = new byte[256];
69 packet = new DatagramPacket(buf, buf.length);
70 try {
71 socket.receive(packet);
72 } catch (IOException e) {
73
74 logger.severe("exception: " + e);
75 break;
76 }
77
78 String received = new String(packet.getData(), 0, packet.getLength());
79 for (Object element : listeners) {
80 MessageListener listener = (MessageListener) element;
81 listener.newMessage(received);
82 }
83 }
84
85 try {
86 socket.leaveGroup(address);
87 } catch (IOException e) {
88
89 logger.severe("exception: " + e);
90 }
91 socket.close();
92 }
93 }