I am doing a simple exercise to understand sockets and server sockets. When myServerSocket = new ServerSocket(0) a port is randomly assigned to the socket. I want to know how I can set the client up to connect to that port. How does the client find the listening port if it is randomly assigned?
Here is the snippets of code from both the server and client classes:
Server:
public static void main(String[] args) {
try {
// First we create a server socket and bind it to a random port.
ServerSocket myServerSocket = new ServerSocket(0);
// wait for an incoming connection...
System.out.println("Server is waiting for an incoming connection on host="
+ InetAddress.getLocalHost().getCanonicalHostName()
+ " port=" + myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
Client:
public static void main(String[] args) {
// create a socket and bind it to the host/port server is listening on.
String host;
int port;
if(args.length==0) {
host = "localhost";
port = 9999;
} else {
host = args[0];
String portStr = args[1];
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
System.out.println("Whoops, invalid port number. Will default to 9999");
port = 9999;
}
}