/**
* Returns a port that is available for use. It walks through the allowed port range attempting to open each one. It returns the first one that it can open after closing it. There still could be a race condition between multiple instances of this all oppened within a very short itme of each other.
* @param min
* @param max
* @return
* @throws IOException
*/
public int generatePort(int min,int max) throws IOException {
ServerSocket socket=new ServerSocket();
int port=bind(socket,min,max - min);
if (port > 0) {
socket.close();
return port;
}
else {
throw new IOException("Unable to bind on to a prt between " + min + " and "+ max);
}
}

Example 24

From project fitnesse, under directory /src/fitnesse/responders/run/slimResponder/.

/**
* Listens for connections from incoming clients.
* @param port the port to listen on.
* @param receiver an object that implements a method which can be called asynchronously when data is received from the client.
* @param passProvider an object that supplies the password that must be entered by a client in order to establish a connection.
* @return A pointer to the new data handling thread, or null ifstartNewThread is false.
* @throws IOException
* @throws StreamCorruptedException if the stream is not a java object stream. For example, this exception is thrown when an HTTP client tries to establish a connection. It can be safely caught and safely re-opened into a non-object stream for furthur processing.
*/
public Thread listenForConnections(int port,DataReceiverIF receiver,PasswordProvider passProvider) throws IOException, StreamCorruptedException {
System.out.println("Waiting for a connection on port: " + port);
ServerSocket server=getServerInstance(port);
Socket serverSocket=server.accept();
String password=passProvider.fetchPassword();
handleConnectionEstablished(serverSocket,receiver,false);
boolean authSucceeded=handleServerSideAuthentication(serverSocket,password);
if (!authSucceeded) {
return null;
}
return startPacketReceivingThread();
}

Example 29

From project hama, under directory /core/src/test/java/org/apache/hama/.