summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKjetil Ørbekk <kjetil.orbekk@gmail.com>2012-02-07 09:33:48 +0100
committerKjetil Ørbekk <kjetil.orbekk@gmail.com>2012-02-07 09:33:48 +0100
commit523d8655d89d07724569dad790f8564ec623167d (patch)
treed6dce9a688bfd2eb638dfa245091e7e2cfbb5d61
parent7e8f0f25129785068db661cab80cc13d658120a4 (diff)
Add interrupt() support to BroadcastListener.
-rw-r--r--same/src/main/java/com/orbekk/net/BroadcastListener.java8
-rw-r--r--same/src/test/java/com/orbekk/net/BroadcastListenerTest.java32
2 files changed, 38 insertions, 2 deletions
diff --git a/same/src/main/java/com/orbekk/net/BroadcastListener.java b/same/src/main/java/com/orbekk/net/BroadcastListener.java
index c0b66e0..8c59300 100644
--- a/same/src/main/java/com/orbekk/net/BroadcastListener.java
+++ b/same/src/main/java/com/orbekk/net/BroadcastListener.java
@@ -11,14 +11,14 @@ import org.slf4j.LoggerFactory;
public class BroadcastListener {
private int port;
private Logger logger = LoggerFactory.getLogger(getClass());
+ DatagramSocket socket;
public BroadcastListener(int port) {
this.port = port;
}
- public DatagramPacket listen() {
+ public synchronized DatagramPacket listen() {
logger.debug("Waiting for broadcast on port " + port);
- DatagramSocket socket;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
@@ -45,6 +45,10 @@ public class BroadcastListener {
return packet;
}
+ public void interrupt() {
+ socket.close();
+ }
+
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
BroadcastListener listener = new BroadcastListener(port);
diff --git a/same/src/test/java/com/orbekk/net/BroadcastListenerTest.java b/same/src/test/java/com/orbekk/net/BroadcastListenerTest.java
new file mode 100644
index 0000000..67d4ece
--- /dev/null
+++ b/same/src/test/java/com/orbekk/net/BroadcastListenerTest.java
@@ -0,0 +1,32 @@
+package com.orbekk.net;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class BroadcastListenerTest {
+ private Logger logger = LoggerFactory.getLogger(getClass());
+
+ @Test
+ public void interruptWorks() throws Exception {
+ final BroadcastListener listener = new BroadcastListener(0);
+
+ Thread t = new Thread() {
+ @Override public void run() {
+ listener.listen();
+ }
+ };
+ t.start();
+
+ while (listener.socket == null) {
+ logger.info("Waiting for listener to start.");
+ Thread.sleep(100);
+ }
+
+ listener.interrupt();
+ t.join();
+ }
+
+}