1 31 package org.objectweb.proactive.core.rmi; 32 33 import java.io.IOException ; 34 import java.io.Serializable ; 35 import java.net.ServerSocket ; 36 import java.net.Socket ; 37 import java.rmi.server.RMIClientSocketFactory ; 38 import java.rmi.server.RMIServerSocketFactory ; 39 import java.util.Random ; 40 41 import org.apache.log4j.Logger; 42 43 47 public class RandomPortSocketFactory implements RMIServerSocketFactory , RMIClientSocketFactory , Serializable { 48 49 50 static Logger logger = Logger.getLogger(RandomPortSocketFactory.class.getName()); 51 52 static protected final int MAX = 5; 53 static protected Random random = new Random (); 54 56 protected int basePort = 35000; 57 protected int range = 5000; 58 59 public RandomPortSocketFactory() { 60 logger.debug("RandomPortSocketFactory constructor()"); 61 } 62 63 64 public RandomPortSocketFactory(int basePort, int range) { 65 logger.debug("RandomPortSocketFactory constructor(2) basePort = " + basePort + " range " + range); 66 this.basePort = basePort; 67 this.range = range; 68 } 69 70 71 public ServerSocket createServerSocket(int port) throws IOException { 72 int tries = 0; 73 logger.debug("RandomPortSocketFactory: createServerSocket " + port + " requested" ); 74 while (true) { 75 try { 76 int offset = random.nextInt(range); 77 ServerSocket socket = new ServerSocket (basePort + offset); 79 logger.debug("RandomPortSocketFactory: success for port " + (basePort + offset)); 80 return socket; 82 } catch (IOException e) { 83 tries++; 84 if (tries > MAX) 85 throw new IOException (); 87 } 88 } 89 } 90 91 92 public Socket createSocket(String host, int port) throws IOException { 93 logger.debug("RandomPortServerSocketFactory: createSocket to host " + host + " on port " + port); 94 return new Socket (host, port); 98 } 103 } 104 | Popular Tags |