Main program:
Code
@Override
public void run() {
while(!messageMain.equals("endProgram")){
try {
messageMain = receiveMessage();
getLogger().info("Message in main: " + messageMain);
} catch (SocketException e) {
e.printStackTrace();
}
}
}
Display More
And thread:
Code
public class UDP_2 implements Runnable {
private DatagramSocket socket;
private boolean running;
private byte[] buf = new byte[256];
public String message = "";
public UDP_2(DatagramSocket socket_){
socket = socket_;
}
public void run() {
running = true;
while (running) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);//we instantiate a DatagramPacket to receive incoming messages.
try {
socket.receive(packet);//This method blocks until a message arrives and it stores the message inside the byte array of the DatagramPacket passed to it.
} catch (IOException e) {
e.printStackTrace();
}
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
String received = new String(packet.getData(), 0, packet.getLength());
received = received.replaceAll("\u0000.*", "");
try {
socket.send(packet);
buf = new byte[256];
running = false;
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
Display More