-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPacketSender.java
67 lines (59 loc) · 1.55 KB
/
PacketSender.java
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
import java.io.IOException;
import java.util.*;
import java.net.*;
public class PacketSender extends TimerTask {
/**
* Constants
*/
private static final long TIMEOUT = 1000;
/**
* Types
*/
private enum State {
NEW,
RUNNING,
TERMINATED;
}
/**
* Properties
*/
private MetaPacket packet;
private DatagramSocket source;
private Timer timer;
private State state;
/**
* Constructor
* @param packet The MetaPacket that contains all information
* about the DatagramPacket
* @param source The DatagramSocket to send out this packet from
*/
public PacketSender(MetaPacket packet, DatagramSocket source) {
// Set properties
this.packet = packet;
this.source = source;
// Initialize timer and state
this.timer = new Timer();
this.state = State.NEW;
}
// Only issue schedule if timer is pristine
public void start() {
if (this.state != State.NEW) return;
this.timer.scheduleAtFixedRate(this, 0, TIMEOUT);
this.state = State.RUNNING;
}
public void stop() {
if (this.state != State.RUNNING) return;
this.timer.cancel();
this.state = State.TERMINATED;
}
@Override
public void run() {
try {
this.source.send(this.packet.getPacket());
} catch (IOException e) {
System.out.println("Error: Packet delivery failed");
this.stop();
System.exit(1);
}
}
}