I have an application that does many things. I'd like to add a method that enables this application to behave like a udp server on a socket. In particular it listens on the localhost address on port 8888. I tried implementing this behaviour with the following code but i get an Address already in use error. Plus the whole application is stuck on this udp server method. I guess its probably due to the fact that its all running on one thread.
1) Can you please show me how to correct my method. In particular how to make this udp server listener start on a new thread.
2) This server will listen forever for pks from the client. Depending on wether the server receveid a specific packet or not it needs to do certain things. Is the logic correct: if the packetReceived is != null and the packet has not been processed then process it. repeat forever (as show in the code)?
public void startSocketListening(){
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket;
System.out.println("Waiting to receive...");
while (true) {
receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
DatagramSocket serverSocket = new DatagramSocket(8888);
serverSocket.receive(receivePacket);
//if i receive a packet and it doesn't already have a flow rule process it
if ((receivePacket != null) && (newOFRuleAdded == false)){
this.rlocAddress = new String(receivePacket.getData());
System.out.println("RECEIVED: " + rlocAddress);
System.out.println("RLOC: " + rlocAddress);
//process the message
newOFRuleAdded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
receivePacketto have become null at the point you are testing for that, by the rules of Java. - user207421