尝试创建DatagramSocket UDP服务器/客户端聊天应用程序,但在收到带有DatagramPacket的数据包后,在更新GUI时遇到一些问题。这是我的代码;我遗漏的唯一一件事,我认为是无关紧要的,是我的JFrame窗口的grouplayout代码。
public class Server extends JFrame {
JButton startServerButton;
JTextField textField;
JTextArea textArea;
public Server() {
super("Server");
initComponents();
setResizable(false);
setVisible(true);
}
private void startServer() throws IOException {
DatagramSocket serverSocket;
String sentence;
startServerButton.setText("Server started");
startServerButton.setEnabled(false);
while (true) {
serverSocket = new DatagramSocket(9876);
// receive
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
int port = receivePacket.getPort();
System.out.println("RECEIVED (port " + port + "): " + sentence);
showMessage("RECEIVED (port " + port + "): " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
// send
byte[] sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
serverSocket.close();
}
}
private void showMessage(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append("\n" + text);
}
});
}
private void initComponents() {
startServerButton = new JButton();
textField = new JTextField();
textArea = new JTextArea();
textArea.setEditable(false);
startServerButton.setText("Start server");
startServerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
startServer();
} catch (IOException e) {
e.printStackTrace();
}
}
});
...grouplayout stuff here...
}
public static void main(String args[]) {
Server server = new Server();
}
}
所以问题是,我的JFrame上的textArea永远不会更新,但我的System.out.println()
总是正确打印从我的Client类收到的消息。我可以显示我的客户端类的代码,但我觉得它是无关紧要的。感谢您的帮助,谢谢。
答案 0 :(得分:2)
您必须在另一个Thread中启动套接字侦听器。否则你会阻止重新绘制。
这样的事情:
startServerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
startServer();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
});