Below class is to launch an UDP listener:
public class Client extends Application {
UdpListener udp = new UdpListener();
public static void main(String[] args) {
Application.launch();
}
@Override
public void start(Stage stage) {
HBox root = new HBox();
Button startListeningButton = new Button("START LISTEN");
Button stopListeningButton = new Button("STOP LISTEN");
Scene scene = new Scene(root);
root.setSpacing(10);
root.getChildren().addAll(startListeningButton, stopListeningButton);
EventHandler<MouseEvent> handlerStartListen = event -> {
try {
udp.run();
}catch (Exception e) {
e.printStackTrace();
}
};
EventHandler<MouseEvent> handlerStopListen = event -> {
//
};
startListeningButton.addEventFilter(MOUSE_CLICKED, handlerStartListen);
stopListeningButton.addEventFilter(MOUSE_CLICKED, handlerStopListen);
stage.setScene(scene);
stage.setTitle("SNIFFER");
stage.show();
stage.sizeToScene();
}
Below UdpListener
:
public class UdpListener implements Runnable {
private final Integer LIST_PORT = 30000;
private final Integer UDP_SIZE = 1472;
private DatagramSocket socket;
private DatagramPacket receivingPacket;
public void run() {
try {
socket = new DatagramSocket(LIST_PORT);
doProcessing();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doProcessing() throws IOException {
while (true) {
String checkAsterix;
String asterixPackData;
byte buff[] = new byte[UDP_SIZE];
receivingPacket = new DatagramPacket(buff, buff.length);
socket.receive(receivingPacket);
buff = receivingPacket.getData();
asterixPackData = new Decode(buff).getHexString();
checkAsterix = asterixPackData.substring(0, Math.min(asterixPackData.length(), 2));
Integer i = Integer.decode("0x" + checkAsterix);
switch (i) {
case (48):
new ShowMessage("TROVATO");
//new atxlib....
break;
default:
new ShowMessage("SCARTO");
break;
}
}
}
}
UdpListener
is another class that just open a socket to sniff all the data to port XXXX and decode them.
I can launch directly the UdpListener
. But if I link this start to the above code the application looks like stuck even if it working.
when I move the mouse cursor on the stage, it change to "loading". Mean time the activity monitor says "java not responding".
Any suggestions?
You're blocking the UI thread with an infinite loop. If you do this, the UI stops responding. You need to run such long running from a different thread:
replace
try {
udp.run();
}catch (Exception e) {
e.printStackTrace();
}
with
new Thread(udp).start();
and use Platform.runLater
to update the ui from the new thread, if necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With