【发布时间】: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