Java – Server Socket Loose Binding (bind)

Server Socket Loose Binding (bind)… here is a solution to the problem.

Server Socket Loose Binding (bind)

I want to develop primary and secondary servers.

When the primary server shuts down, the secondary server should start on the same port.

But when the primary server

is ready to start, the secondary server should stop gracefully so that the primary server can start on the same port.

Is there any way to let the secondary server know that another process is trying to start on the same port?

Solution

If you need to keep your server running all the time, you can follow this method

Create a parent process that spawns a child process to perform the actual service by listening on the port. While the child process is processing the actual request, the parent process will use the waitpid in C to wait for the child process to die (crash/state change). Therefore, whenever a child fails, the parent knows about it and spawns a new process. – Preferred method.


If you especially need the main and auxiliary design,

When a secondary service is requested, it can always wait for a signal from the primary server. Therefore, when Master starts, its first task is to send that signal to Secondary when it finds that Secondary started (via a pid file or file locking or binding (bind) failed) so that Secondary can shut down gracefully.

Related Problems and Solutions