You can bind two servers to the same port if you specify two different interfaces:
ServerSocket s1 = new ServerSocket(port, 500, InetAddress.getByName("127.0.0.1"));
ServerSocket s2 = new ServerSocket(port, 500, InetAddress.getByName("127.0.0.2"));
Pregunta
I want to run two instance of same server on same physical machine. These two servers will listen to same port, say 12345. I am trying run one server on 127.0.0.1, and the other one on 127.0.0.2. These two servers will basically send and receive messages using same port but running on separate loopback addresses. I do not know if I am on correct path to set this test environment? Somehow, I am not able to setting this testing environment. I am using java to develop the server.
Solución
You can bind two servers to the same port if you specify two different interfaces:
ServerSocket s1 = new ServerSocket(port, 500, InetAddress.getByName("127.0.0.1"));
ServerSocket s2 = new ServerSocket(port, 500, InetAddress.getByName("127.0.0.2"));
Otros consejos
That's exactly what my fork of NanoHTTPD was intended for:
https://github.com/gitgrimbo/nanohttpd/commit/9535d1b6b4c1bbc927d390327018882d84df959f
Added ability to specify hostname to bind to.
For example:
java NanoHTTPD -d wwwroot1 -h 127.0.0.1
java NanoHTTPD -d wwwroot2 -h 127.0.0.2
java NanoHTTPD -d wwwroot3 -h 127.0.0.3
And hosts file:
127.0.0.1 www1.example.com
127.0.0.2 www2.example.com
127.0.0.3 www3.example.com
Specifically line 225 (in the commit link above):
myServerSocket.bind(new InetSocketAddress(hostname, port));
This code, combined with my instructions above, show how you can run a server on several loopback addresses, all using the same port (80 by default, but could be any of your choice).