0

I have a server - client pair written in java and I would like to quit one application if the other one is quit. How is this done? I would also like to know how to make the program do a sequence of commands (e.g. close sockets etc.) if the user quits the application manually (i.e. by pressing cmd+q.alt+F4 etc.)

Samantha Catania
  • 5,116
  • 5
  • 39
  • 69

2 Answers2

1

Usually the way to do it would be to have a heartbeat thread running separately. The way this works is -

  1. Each client runs a heartbeat thread and will send periodic message to the server essentially saying that "I am running". You can tweak the timing between the message as per your requirement.

  2. The server runs a heartbeat listener thread and will maintain a list of clients running

  3. Once all the clients stop sending message the server can wait a couple of minutes and then gracefully shut down.

This design can work for a single client or many clients.

Pushkar
  • 7,450
  • 10
  • 38
  • 57
  • I'm a fan of using heartbeats when needed but here the problem is that any unreliability in the network and you'd "think" the program was closed. A "network connection lost" is not the same as "I quit the server, I want the client to quit too". I'd rather send a message "I'm going down, so should you" for proper exit while using the heartbeat to just print out a "network connection lost" message. – TacticalCoder Nov 25 '11 at 20:02
  • @user988052 : Well if you are worrying about heartbeat messages being lost in the network then how can you be sure that the "I'm going down, so should you" message will reach the server? Also we are not taking about sending the heartbeat over UDP, we are using TCP sockets which has reliability build in. On top of this you can build redundancy e.g. if no heartbeat received over 1 min then server will shut down. This method is better than client telling the server that i am shutting down as the client may crash and may never get to send the message. – Pushkar Nov 26 '11 at 04:48
  • network rule number one: *"The network is unreliable"*. TCP or not, that is considered the first and most important network rule. Then I am *not* talking about being sure that the "going down" message will reach the server. I am talking about using the correct message when the server goes down. Sure, you may miss a message if the network just so happens to be down while you sent the "going down" message, but doing it this way there's no false positive. This is very, different than relying on the network to be reliable (it is not, that is the network rule number one). – TacticalCoder Nov 26 '11 at 11:13
1

When one quits, it send a message to the other which causes it to quit.

One approach is the poison pill message/object which cause the receiver to shut down when that message is reached.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130