-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.java
More file actions
55 lines (46 loc) · 1.25 KB
/
Node.java
File metadata and controls
55 lines (46 loc) · 1.25 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
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 = 65536;
static 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();
}
public void run() { //Listen for incoming packets and inform receivers
try
{
latch.await();
while (true) // Endless loop: attempt to receive packet, notify receivers, etc
{
DatagramPacket packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);
socket.receive(packet);
onReceipt(packet);
}
}
catch (Exception e)
{
if (!(e instanceof SocketException)) e.printStackTrace();
}
}
}
}