开发者

How to do an action on process terminating?

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 se开发者_开发百科rver 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜