I have a client server application. When multiple clients are connected to the server on a specified port say 6001, I am facing a problem. The problem is when the clients are connected to server and if I stop the server using a script with command kill -9 $pid (where pid is the server app pid), then while restarting the server I get an BIND Exception- Address already in use that means port 6001 is still not available for clients to connect again due to which clients fail to connect to server.
I was looking for a way to resolve this. I have one thought of using range of ports dynamically.
Here is what I am thinking :
In the Xml file instead of hard coding the port number as 6001. I will provide a range of ports say 6001-6005. Then when the server starts it will loop through the ports to choose the available port. For example - when the server tries to attempt to create a server socket bound to the specified port 6001, if there is an exception that if the port is already bound by another application, then it will choose 6002 port and so on. Whichever port will be available, the server will create the server Socket object for it and start listening for clients on that port.
Now similarly on client side it will first attempt to connect on 6001, if fails then 6002 and so on until it connects to right port on which server is listening to.
My question is if this is the right approach. Also if a client can connect in such a way mentioned above.
if No, then is there any there way to solve the issue which I mentioned above.