为什么用于UDP服务器的Javafx GUI停止工作



我创建了一个UDP服务器,它总是在侦听从客户端获取数据。单独的服务器(没有GUI(运行良好,可以完成所有需要的操作。我使用javafx为它制作了一个简单的GUI,这样当用户按下按钮时,服务器就会开始工作并跟踪收到的数据包。但当我点击启动按钮时,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;
}

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

与其调用main,不如让Server类实现Runnable。然后,当点击按钮时,您可以实例化一个服务器并启动它,这将返回允许启动方法返回

最新更新