如何在进程终止时执行操作?
我用 Java 编写了一个程序,它为一个简单的在线游戏创建套接字连接。该服务器是多客户端的,并且有一个已记录的用户列表。当我关闭客户端时,它会向服务器发送一条消息以注销用户。我还希望当客户端通过 Eclipse(或 Windows 任务管理器)的“终止”按钮终止时,客户端会发送相同的消息。我尝试使用 ShootdownHook 但它不起作用。有什么想法吗? 谢谢。
I have written a program in Java which creates a socket connection for a simple online game. The server is multiclient and has a list of users logged. When I close the client it sends to the server a message to log out the user. I also want that when the client is terminated with the "terminate" button of Eclipse (or with Windows task manager) the client sends the same message. I tried with a ShootdownHook but it does not work. Any idea?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果出现 Eclipse 中的红色方块,您在客户端无法采取任何行动。它以“极端偏见”终止 jvm——没有代码运行。没有钩子,什么也没有。
正如@Dilum 所解释的,你必须在服务器端应对。
Nothing you can on the client side can act in the event of the red square in Eclipse. It terminates the jvm 'with extreme prejudice' -- no code runs. No hooks, no nothing.
You have, as @Dilum explained, to cope on the server side.
为了拥有一个健壮的系统,您有时需要实现一个允许服务器关闭连接的心跳机制。例如,如果客户端在过去 30 秒内没有设置心跳,则关闭连接。考虑一下客户端和服务器之间的网络出现故障的情况……或者客户端运行的机器死掉了。在这些情况下,您不能依赖客户端的注销消息到达服务器。
话虽如此,我怀疑 shutdown hook 来不及进行实际的网络 IO。我已成功使用关闭挂钩来关闭连接。因此,您需要进行更正式的关闭,在启动其他关闭活动(尤其是关闭连接)之前发送消息。
In order to have a robust system, you will at some point need to implement a heartbeat mechanism that allows the server to close connections. For example, if a client hasn't set a heartbeat in the last 30 seconds, then close the connection. Consider the case where the network between client and server goes down... or the machine the client is running on dies an ugly death. In those cases, you cannot rely on the client's logout message getting to the server.
Having said that, I suspect that shutdown hook is too late to do actual network IO. I have successfully used shutdown hooks to close connections. So you will need to have a more formal shutdown where the message is sent before other shutdown activity -- especially closing connections -- is initiated.