-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.java
More file actions
59 lines (49 loc) · 1.24 KB
/
Copy pathNode.java
File metadata and controls
59 lines (49 loc) · 1.24 KB
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
/**
* @author Thomas Moroney
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.CountDownLatch;
public abstract class Node {
static final int PACKETSIZE = 1000;
static final int PADDING = 20;
DatagramSocket socket;
Listener listener;
CountDownLatch latch;
Node() {
latch= new CountDownLatch(1);
listener= new Listener();
listener.setDaemon(true);
listener.start();
}
public abstract void onReceipt(DatagramPacket packet);
/**
*
* Listener thread
*
* Listens for incoming packets on a datagram socket and informs registered receivers about incoming packets.
*/
class Listener extends Thread {
/*
* Telling the listener that the socket has been initialized
*/
public void go() {
latch.countDown();
}
/*
* Listen for incoming packets and inform receivers
*/
public void run() {
try {
latch.await();
// Endless loop: attempt to receive packet, notify receivers, etc
while(true) {
DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
socket.receive(packet);
onReceipt(packet);
}
} catch (Exception e) {if (!(e instanceof SocketException)) e.printStackTrace();}
}
}
}