Java 中退出 JFrame 和 TCP 通信之前关闭资源
1. 我正在编写一个基于 TCP 通信的聊天应用程序。 我正在使用 NetBeans,我想在退出 JFrame 时向默认的 EXIT_ON_CLOSE 添加功能。 原因当然是因为我想清理资源并安全地结束线程。 如何调用一个方法来清除资源,然后安全地关闭 JFrame 并结束进程。
2. 我需要实现服务器端。服务器有“Socket”的列表/哈希映射/队列及其聊天昵称。是否有任何简单的设计模式可以正确完成它,因为我不想重新发明轮子。
谢谢。
1.
I'm writing a chat based application on TCP communication.
I'm using NetBeans and I want to add functionality to the default EXIT_ON_CLOSE when exiting JFrame.
The reason of course is because I want to clean resources and end threads safely.
How can I call a method that clear resources and only then close the JFrame safely and end the process.
2.
I need to implement the server side. The server has List/HashMap/Queue of 'Socket' with their chat nick-names. Is there any simple design pattern to do it correctly because I don't want to re-invent the wheel.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在尝试了安德鲁的建议并尝试自己解决这个问题之后,这就是我所做的。就我而言,我将数据保存到数据库,而您则关闭 TCP 通信。这个想法保持不变:在关闭窗口和程序实际关闭之间我们有工作要做。
After attempting Andrew's suggestion in trying to solve this problem myself, here's what I did. In my case, I'm saving data to a database, while you're closing tcp communication. The idea remains the same: we have work to do between when we close the window and when the program actually closes.
您可以使用 WindowAdapter 类来保存 WindowListener 接口的所有方法的实现(它包括每个方法的空实现,以便您可以覆盖您关心的方法)。
You can use the WindowAdapter class to save implementing all the methods of the WindowListener interface (it includes an empty implementation of each method so you can override the ones you care about).
对于第1)点,设置
JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
,向框架添加一个WindowListener
。在 close 方法中,添加结束Thread
的功能。清理资源。实现 Runtime.addShutdownHook(Thread) 也可能是值得的。请注意,关闭挂钩应该快速完成。
For point 1), set the
JFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
, add aWindowListener
to the frame. In the close method, add the functionality to end theThread
s & clear the resources.It might also pay to implement
Runtime.addShutdownHook(Thread)
. Note that a shutdown hook should complete quickly.对于第二点:当我编写一个类似的程序时,我创建了一个名为“Connection”的类,其中包含一个套接字和一个字符串昵称作为成员。该类扩展了 Thread 类。
因此,每当创建一个新套接字时,它就会被插入到这样一个对象中,然后该对象将作为单独的线程运行,侦听新消息。每当创建对象时,这些对象都会插入到列表中,然后在用户退出时根据需要删除。
For point 2: When I wrote a similar program I created a class called "Connection" which included as members a socket and a string nickname. The class extended the Thread class.
So, whenever a new socket was created it would be inserted into such an object which would then run as a separate thread, listening for new messages. These objects were inserted to into a list whenever one was created and then deleted as appropriate when the user signed off.