summaryrefslogtreecommitdiffstats
path: root/src/main/java/derms/replica2/Announcer.java
blob: 508349efcaad081a90392918f50c1539bbaa3398 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package derms.replica2;

import java.io.IOException;
import java.net.*;
import java.util.logging.Logger;

class Announcer implements Runnable {
	static final long intervalMillis = 3000;

	private SocketAddress group;
	private InetAddress localAddr;
	private City city;
	private Logger log;

	Announcer(SocketAddress group, InetAddress localAddr, City city) throws IOException {
		this.group = group;
		this.localAddr = localAddr;
		this.city = city;
		this.log = DermsLogger.getLogger(this.getClass());
	}

	@Override
	public void run() {
		NetworkInterface netInterface = null;
		try {
			netInterface = NetworkInterface.getByInetAddress(localAddr);
			if (netInterface == null) {
				throw new Exception("netInterface is null");
			}
		} catch (Exception e) {
			log.severe("Failed to get network interface bound to "+localAddr.toString()+": "+e.getMessage());
			return;
		}

		MulticastSocket sock = null;
		try {
			sock = new MulticastSocket();
			sock.joinGroup(group, netInterface);
		} catch (Exception e) {
			log.severe("Failed to open multicast socket: "+e.getMessage());
			return;
		}

		log.info("Announcing from "+localAddr.toString()+" ("+netInterface.getName()+") to "+group.toString());

		DatagramPacket pkt = null;
		try {
			pkt = ObjectPacket.create(city, group);
		} catch (IOException e) {
			log.severe("Failed to create packet: "+e.getMessage());
			sock.close();
			return;
		}

		try {
			for (;;) {
				sock.send(pkt);
				Thread.sleep(intervalMillis);
			}
		} catch (IOException e) {
			log.severe("Failed to send to multicast socket "+group.toString()+": "+e.getMessage());
		} catch (InterruptedException e) {
			log.info("Interrupted.");
		} finally {
			log.info("Shutting down...");
			sock.close();
		}
	}
}