【问题标题】:Why Javafx GUI for UDP Server stops working为什么 UDP 服务器的 Javafx GUI 停止工作
【发布时间】:2021-06-08 14:39:46
【问题描述】:

我创建了一个 UDP 服务器,它始终在监听以从客户端获取数据。单独的服务器 - 没有 GUI - 可以正常工作并且满足所有要求。我使用 javafx 为它制作了一个简单的 GUI,因此当用户按下按钮时,服务器开始工作并跟踪接收到的数据包。但是当我点击开始按钮 GUI 停止工作。我做错了什么?

图形用户界面

@FXML
//buttons
public Button start_btn;

//text boxes to enter values
public TextField sentPackets;


@FXML
private void start_btnClicked() throws IOException, InterruptedException, SQLException {

    Server obj = new Server();
    obj.main(null);
}

服务器

public static void main(String[] args) throws IOException, SQLException {

    System.out.println("-------------------Server Listening-------------------");

    String line;

    // Step 1 : Create a socket to listen at port 1234
    DatagramSocket ds = new DatagramSocket(1234);
    byte[] receive = new byte[65535];

    DatagramPacket DpReceive = null;

    while (true) {

        // Step 2 : create a DatgramPacket to receive the data.
        DpReceive = new DatagramPacket(receive, receive.length);

        // Step 3 : revieve the data in byte buffer.
        ds.receive(DpReceive);

        System.out.println("Client:-" + data(receive));

        line = data(receive).toString();

        String str = line;
        String[] arrOfStr = str.split("@", 100);


        db obj = new db();
        obj.DB(arrOfStr);


        // Clear the buffer after every message.
        receive = new byte[65535];
    }

}
// A utility method to convert the byte array
// data into a string representation.
public static StringBuilder data(byte[] a)
{
    if (a == null)
        return null;
    StringBuilder ret = new StringBuilder();
    int i = 0;
    while (a[i] != 0)
    {
        ret.append((char) a[i]);
        i++;
    }
    return ret;
}

【问题讨论】:

  • 您在 FX 应用程序线程上运行无限循环,阻止 FX 应用程序线程进行正常工作(绘制 UI、处理用户事件等)。反正你在这里做什么还不是很清楚。 main(...) 方法是应用程序的入口点;如果你在代码中调用它,你几乎肯定做错了什么。
  • 请遵守 java 命名约定

标签: java maven javafx crash udp


【解决方案1】:

您的 main 方法位于 while (true) 循环中,因此 start_btnClicked 方法永远不会返回。

为什么不让你的 Server 类实现 Runnable,而不是调用 main。然后,当单击按钮时,您可以实例化一个服务器并启动它,这将返回允许启动方法返回

【讨论】:

  • 非常感谢您,一直使用您的解决方案修复它。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多