diff options
author | Kjetil Ørbekk <kjetil.orbekk@gmail.com> | 2012-02-07 09:34:28 +0100 |
---|---|---|
committer | Kjetil Ørbekk <kjetil.orbekk@gmail.com> | 2012-02-07 09:34:28 +0100 |
commit | 166b70fce6021e8f6cc9d8f0fa968c05a26aced2 (patch) | |
tree | cfda99142bf25b3f2367c4d9a2d2ef3156516740 /same | |
parent | bd2a0390a6bd6c672bd1416d6894ac646128e9e2 (diff) |
Add DiscoveryService.
Diffstat (limited to 'same')
-rw-r--r-- | same/src/main/java/com/orbekk/same/DiscoveryService.java | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/same/src/main/java/com/orbekk/same/DiscoveryService.java b/same/src/main/java/com/orbekk/same/DiscoveryService.java new file mode 100644 index 0000000..bc28a58 --- /dev/null +++ b/same/src/main/java/com/orbekk/same/DiscoveryService.java @@ -0,0 +1,44 @@ +package com.orbekk.same; + +import java.net.DatagramPacket; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.orbekk.net.BroadcastListener; + +public class DiscoveryService extends Thread { + private Logger logger = LoggerFactory.getLogger(getClass()); + BroadcastListener broadcastListener; + DiscoveryListener listener; + + public DiscoveryService(int port, DiscoveryListener listener, + BroadcastListener broadcastListener) { + this.listener = listener; + this.broadcastListener = broadcastListener; + } + + public void run() { + while (!Thread.interrupted()) { + DatagramPacket packet = broadcastListener.listen(); + String content = new String(packet.getData(), 0, packet.getLength()); + String[] words = content.split(" "); + + if (!content.startsWith("Discover") || words.length < 2) { + logger.warn("Invalid discovery message: {}", content); + continue; + } + + String url = words[1]; + logger.info("Received discovery from {}", url); + if (listener != null) { + listener.discover(url); + } + } + } + + @Override public void interrupt() { + super.interrupt(); + broadcastListener.interrupt(); + } +} |