I'm a beginner in java. I have a device that sends UDP broadcast ping packets every 5s, and rarely sends an alert (a kind of alarm).
I want to have a java program that listens for the ping packets and shows how long since the last ping, and sets off an alarm of some kind either if a ping is not received for a certain amount of time, or if an actual alert from the sensor is received.
I've shamelessly copied this code from stackoverflow, but the serverSocket.receive(receivePacket)
blocks, so the counter does not work.
I think that I need to spawn a thread to open the socket and wait for received data, and then communicate back to the main thread somehow without blocking so the timer can run, but I have no idea how to achieve that.
Here's the code I have so far - it works but the timer does not work to show the time since the last ping:
package com.testing;
import java.io.IOException;
import java.net.*;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Receiver { // from https://stackoverflow.com/a/13780614/1340782
public static void main(String[] args) {
int port = args.length == 0 ? 8266 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "pong";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
LocalTime lastPing = java.time.LocalTime.now();
String lastMessage = "";
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
// System.out.println(java.time.LocalTime.now().truncatedTo(ChronoUnit.SECONDS) + " RECEIVED: " + sentence);
LocalTime now = java.time.LocalTime.now();
lastMessage = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"))
+ " RECEIVED: " + sentence;
if (sentence.equals("ping")) {
lastPing = java.time.LocalTime.now();
}
lastMessage = lastMessage + " - " + Duration.between(lastPing,now).toMillis() + "ms since last ping";
System.out.print(lastMessage);
System.out.print("\r");
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
Thanks everyone