下面的类是启动UDP侦听器:
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();
}
低于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
是另一个只打开套接字来嗅探所有数据到端口XXXX并解码它们的类。
我可以直接启动UdpListener
。 但是如果我将这个开头链接到上面的代码,即使它正常工作,应用程序也会停滞不前。
当我在舞台上移动鼠标光标时,它会变为“加载”。 活动监视器说“java没有响应”的平均时间。
有什么建议吗?
答案 0 :(得分:3)
您使用无限循环阻止UI线程。如果执行此操作,UI将停止响应。你需要从不同的线程运行这么长时间的运行:
替换
try {
udp.run();
}catch (Exception e) {
e.printStackTrace();
}
与
new Thread(udp).start();
并使用Platform.runLater
在必要时从新线程更新ui。