I am currently working on Java homework. I am invited to create a basic DNS server. There is a UDPSender class, which is a stream listening on port 53. There is also another stream called UDPManager.
UDPManager starts a stream with a nested runnable class that contains an ArrayList from the DatagramPacket. UDPSender combines the UDPManager and whenever it receives a UDP packet, it sends it to the manager to add it to the array list.
import java.net.DatagramPacket; import java.util.ArrayList; import java.util.HashMap; public class UDPManager { private UDPManagerRunnable manager; public UDPManager(String hostsFile, String remoteDNS, boolean localResolution) { manager = new UDPManagerRunnable(hostsFile, remoteDNS, localResolution); new Thread(manager).start(); } public void managePacket(DatagramPacket p) { manager.managePacket(p); } public void close() { manager.close(); } private class UDPManagerRunnable implements Runnable { private ArrayList<DatagramPacket> packets; private HashMap<Integer, String> clients; private boolean localResolution; private boolean running; private String hostsFile; private String remoteDNS; public UDPManagerRunnable(String hostsFile, String remoteDNS, boolean localResolution) { packets = new ArrayList<DatagramPacket>(); clients = new HashMap<Integer, String>(); this.localResolution = localResolution; this.running = true; this.hostsFile = hostsFile; this.remoteDNS = remoteDNS; } public void managePacket(DatagramPacket p) { packets.add(p); System.out.println("Received packet. "+packets.size()); } public void close() { running = false; } public void run() { DatagramPacket currentPacket = null; while(running) { if(!packets.isEmpty()) { currentPacket = packets.remove(0); byte[] data = currentPacket.getData(); int anCountValue = data[Constant.ANCOUNT_BYTE_INDEX]; if(anCountValue == Constant.ANCOUNT_REQUEST) this.processRequest(currentPacket); else if(anCountValue == Constant.ANCOUNT_ONE_ANSWER) this.processResponse(currentPacket); } } } private void processRequest(DatagramPacket packet) { System.out.println("it a request!"); } private void processResponse(DatagramPacket packet) { System.out.println("it a response!"); } }
}
This is UDPManager. Packets are correctly sent to the dispatcher, because System.out.println correctly displays the "Received packet". and the size of the array increases. The problem I am facing is that inside "run ()" it never sees an increase in size. The strange thing is that it works great in debugging. Any idea why this is so acting?
Many thanks for your help.
source share