In Java, I need to take the port number for communication between multiple instances of the same program. Now I could just pick a fixed number and go with it. But I am wondering if there is a way to dynamically select the port number, so I donβt need to bother my users with the port number setting.
Here was one idea that works as follows:
- There is a fixed starting port number A.
- MyApp starts up, trying to capture port A.
- If this succeeds, then this is the first instance of "MyApp". Done.
- If this fails, it asks through port A whether the program on A is an instance of "MyApp". If so, communicate with this instance. Done. If not, try to capture port A + 1. And if there is another program using this port (and not an instance of "MyApp"), then take A + 2, then A + 3, etc.
Does this strategy make sense? Or is there a better way to dynamically select a port number?
java tcp
python dude
source share