我正在创建一个多人游戏,但是当我创建ServerSocket时,我无法关闭在该应用程序中运行的任何JFrame,这是我的服务器创建代码:
private void createServer() {
JFrame frame = new JFrame("Cow Invaders - Server");
JTextArea console = new JTextArea();
frame.setSize(640, 480);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
console.setFont(new Font("Times New Roman", Font.BOLD, 15));
console.setLineWrap(true);
frame.add(console);
frame.setVisible(true);
try {
server = new ServerSocket(Integer.parseInt(port));
System.out.println("No problems here");
} catch (IOException e) {
System.err.println("An error has occurred: " + e.getMessage());
e.printStackTrace();
}
console.append("Started server on port " + port + " and with an IP of " + server.getInetAddress());
try {
socket = server.accept();
} catch (IOException e) {
e.printStackTrace();
System.err.println("An error has occurred: " + e.getMessage());
}
console.append("\n" + "Connection from: " + socket.getInetAddress());
try {
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.err.println("An error has occurred: " + e.getMessage());
e.printStackTrace();
}
try {
out.writeUTF("You have successfully joined the game.");
} catch (IOException e) {
System.err.println("An error has occurred" + e.getMessage());
e.printStackTrace();
}
System.out.println("Successfully send data.");
}
关于导致这种情况的任何想法?
答案 0 :(得分:4)
您似乎在单个线程上执行所有操作,包括使用阻塞代码,这将阻止Swing事件线程,从而阻止它执行必要的活动。我猜这个代码你的JFrame被冻结了。建议:
有关详情,请查看Lesson: Concurrency in Swing。