Search code examples
javamavenjavafxcrashudp

Why Javafx GUI for UDP Server stops working


I have created a UDP server that is always listening to get data from clients. The server alone- without GUI- works fine and does all required. I made a simple GUI for it using javafx, so that when the user presses on a button, the server starts working and keeps track of received packets. But when I click on the start button GUI stops working. what am I doing wrong?

The 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);
}

Server

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;
}

Solution

  • Your main method sits in the while (true) loop, so the start_btnClicked method never returns.

    Instead of calling main, why not make your Server class implement Runnable. Then, when the button is clicked you can instantiate a Server and start it, which will return allow the start method to return