1 |
import java.io.*; |
2 |
import java.net.*; |
3 |
import java.util.*; |
4 |
|
5 |
// This class contains the main method to be run by |
6 |
// the filter children. It harvests UDP traffic. |
7 |
// |
8 |
// |
9 |
public class UDPReader extends Thread{ |
10 |
|
11 |
// It is normal to use this constructor in preference |
12 |
// to any other in this class. |
13 |
public UDPReader(int port, Logger logger){ |
14 |
this.logger = logger; |
15 |
this.port = port; |
16 |
} |
17 |
|
18 |
public UDPReader(Logger logger){ |
19 |
this(4589, logger); |
20 |
} |
21 |
|
22 |
public void run() { |
23 |
|
24 |
DatagramSocket socket = null; |
25 |
try { |
26 |
socket = new DatagramSocket(port); |
27 |
} |
28 |
catch (BindException e){ |
29 |
logger.write(this.toString(), Logger.SYSMSG, "Could not start the UDPReader thread on port "+port+" as this port was already in use."); |
30 |
return; |
31 |
} |
32 |
catch (Exception e){ |
33 |
logger.write(this.toString(), Logger.SYSMSG, "Could not start the UDPReader thread on port "+port+"."); |
34 |
return; |
35 |
} |
36 |
|
37 |
logger.write(this.toString(), Logger.SYSMSG, "UDPReader thread ready and listening for UDP packets on port "+port); |
38 |
|
39 |
byte[] buf; |
40 |
|
41 |
boolean running = true; |
42 |
while (running){ |
43 |
try { |
44 |
buf = new byte[packetSizeLimit]; |
45 |
// receive request |
46 |
DatagramPacket packet = new DatagramPacket(buf, buf.length); |
47 |
socket.receive(packet); |
48 |
UDPReaderThread t = new UDPReaderThread(); |
49 |
t.run(packet); |
50 |
} |
51 |
catch (IOException e) { |
52 |
logger.write(this.toString(), Logger.SYSMSG, "The UDPReader thread has been shut down as an exception occured: "+e); |
53 |
return; |
54 |
} |
55 |
} |
56 |
socket.close(); |
57 |
} |
58 |
|
59 |
|
60 |
Logger logger; |
61 |
int port; |
62 |
|
63 |
final int packetSizeLimit = 8192; |
64 |
|
65 |
} |