类java.net.BindException源码实例Demo

下面列出了怎么用java.net.BindException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: openjdk-8   文件: RmiBootstrapTest.java
/**
 * Test a configuration file which should make the bootstrap fail.
 * The test is assumed to have succeeded if the bootstrap fails.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationKo(File conf,int port) {
    String errStr = null;
    for (int i = 0; i < PORT_TEST_LEN; i++) {
        try {
            errStr = testConfiguration(conf,port+testPort++);
            break;
        } catch (BindException e) {
            // port conflict; try another port
        }
    }
    if (errStr == null) {
        return "Configuration " +
            conf + " should have failed!";
    }
    System.out.println("Configuration " +
                       conf + " failed as expected");
    log.debug("runko","Error was: " + errStr);
    return null;
}
 
源代码2 项目: reef   文件: HttpServerImpl.java
private Server tryPort(final int portNumber) throws Exception {
  Server srv = new Server();
  final Connector connector = new SocketConnector();
  connector.setHost(this.hostAddress);
  connector.setPort(portNumber);
  srv.addConnector(connector);
  try {
    srv.start();
    LOG.log(Level.INFO, "Jetty Server started with port: {0}", portNumber);
  } catch (final BindException ex) {
    srv = null;
    LOG.log(Level.FINEST, "Cannot use host: {0},port: {1}. Will try another",
        new Object[] {this.hostAddress, portNumber});
  }
  return srv;
}
 
源代码3 项目: fastjgame   文件: NettyThreadManager.java
/**
 * 在某个端口范围内选择一个端口监听.
 *
 * @param host        地址
 * @param portRange   端口范围
 * @param sndBuffer   socket发送缓冲区
 * @param rcvBuffer   socket接收缓冲区
 * @param initializer channel初始化类
 * @return 监听成功的端口号,失败返回null
 */
public DefaultSocketPort bindRange(String host, PortRange portRange, int sndBuffer, int rcvBuffer, ChannelInitializer<SocketChannel> initializer) throws BindException {
    if (portRange.startPort <= 0) {
        throw new IllegalArgumentException("fromPort " + portRange.startPort);
    }
    if (portRange.startPort > portRange.endPort) {
        throw new IllegalArgumentException("fromPort " + portRange.startPort + " toPort " + portRange.endPort);
    }
    for (int port = portRange.startPort; port <= portRange.endPort; port++) {
        try {
            return bind(host, port, sndBuffer, rcvBuffer, initializer);
        } catch (BindException e) {
            // ignore
        }
    }
    throw new BindException("can't bind port from " + portRange.startPort + " to " + portRange.endPort);
}
 
源代码4 项目: sdl_java_suite   文件: SiphonServer.java
private boolean findOpenSocket(short port) {
		// Accept incoming sihpon connection from trace utility.
		Boolean foundOpenPort = false;
		listenPort = port;
		
		// Listen to accept incoming connection from SDL
		while (!foundOpenPort) {
 		try {
 			m_listeningSocket = new ServerSocket(listenPort);
 			foundOpenPort = true;
 			m_listenPort = listenPort;
 		} catch (BindException ex) {
 			listenPort++;
 			if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) {
 				return false;
 			}
 		} catch (IOException e) {
 			return false;
}
		}
		
		return foundOpenPort;
	}
 
源代码5 项目: gemfirexd-oss   文件: PortHelper.java
/**
 * Returns true if a cause of the given (non-null) exception is a
 * BindException with message containing {@link #ADDRESS_ALREADY_IN_USE}.
 * or a SocketException with message containing {@link #UNRECOGNIZED_SOCKET}.
 */
public static boolean addressAlreadyInUse(Throwable t) {
  if (t == null) {
    throw new IllegalArgumentException("Exception cannot be null");
  }
  Throwable root = t;
  while (root != null) {
    if (root instanceof BindException &&
        root.getMessage() != null &&
        root.getMessage().contains(ADDRESS_ALREADY_IN_USE)) {
      Log.getLogWriter().warning("Got BindException: " + ADDRESS_ALREADY_IN_USE);
      return true;
    }
    if (root instanceof SocketException &&
        root.getMessage() != null &&
        root.getMessage().contains(UNRECOGNIZED_SOCKET)) {
      Log.getLogWriter().warning("Got SocketException: " + UNRECOGNIZED_SOCKET);
      return true;
    }
    root = root.getCause();
  }
  return false;
}
 
源代码6 项目: jdk8u-jdk   文件: RmiBootstrapTest.java
/**
 * Test a configuration file. Determines whether the bootstrap
 * should succeed or fail depending on the file name:
 *     *ok.properties: bootstrap should succeed.
 *     *ko.properties: bootstrap or connection should fail.
 * @return null if the test succeeds, an error message otherwise.
 **/
private String testConfigurationFile(String fileName) {
    File file = new File(fileName);
    final String portStr = System.getProperty("rmi.port",null);
    final int port       = portStr != null ?
                            Integer.parseInt(portStr) : basePort;

    if (fileName.endsWith("ok.properties")) {
        String errStr = null;
        for (int i = 0; i < PORT_TEST_LEN; i++) {
            try {
                errStr = testConfiguration(file,port+testPort++);
                return errStr;
            } catch (BindException e) {
                // port conflict; try another port
            }
        }
        return "Can not locate available port";
    }
    if (fileName.endsWith("ko.properties")) {
        return testConfigurationKo(file,port+testPort++);
    }
    return fileName +
        ": test file suffix must be one of [ko|ok].properties";
}
 
源代码7 项目: j2objc   文件: SinkChannelTest.java
public void test_socketChannel_read_write() throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    try {
      ssc.socket()
          .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0 /* any free port */));
    } catch (BindException e) {
      // Continuous build environment doesn't support localhost sockets.
      return;
    }
    int localPort = ssc.socket().getLocalPort();
    SocketChannel sc = SocketChannel.open();
    sc.connect(new InetSocketAddress(InetAddress.getLocalHost(), localPort));
    SocketChannel sock = ssc.accept();
    ByteBuffer[] buf = {ByteBuffer.allocate(10),null};
    try {
        sc.write(buf,0,2);
        fail("should throw NPE");
    } catch (NullPointerException expected) {
    }
    ssc.close();
    sc.close();
    ByteBuffer target = ByteBuffer.allocate(10);
    assertEquals(-1, sock.read(target));
}
 
源代码8 项目: hbase   文件: MasterRpcServices.java
@Override
protected RpcServerInterface createRpcServer(final Server server,
    final RpcSchedulerFactory rpcSchedulerFactory, final InetSocketAddress bindAddress,
    final String name) throws IOException {
  final Configuration conf = regionServer.getConfiguration();
  // RpcServer at HM by default enable ByteBufferPool iff HM having user table region in it
  boolean reservoirEnabled = conf.getBoolean(ByteBuffAllocator.ALLOCATOR_POOL_ENABLED_KEY,
    LoadBalancer.isMasterCanHostUserRegions(conf));
  try {
    return RpcServerFactory.createRpcServer(server, name, getServices(),
        bindAddress, // use final bindAddress for this server.
        conf, rpcSchedulerFactory.create(conf, this, server), reservoirEnabled);
  } catch (BindException be) {
    throw new IOException(be.getMessage() + ". To switch ports use the '"
        + HConstants.MASTER_PORT + "' configuration property.",
        be.getCause() != null ? be.getCause() : be);
  }
}
 
源代码9 项目: sdl_java_suite   文件: SiphonServer.java
private boolean findOpenSocket(short port) {
		// Accept incoming sihpon connection from trace utility.
		Boolean foundOpenPort = false;
		listenPort = port;
		
		// Listen to accept incoming connection from SDL
		while (!foundOpenPort) {
 		try {
 			m_listeningSocket = new ServerSocket(listenPort);
 			foundOpenPort = true;
 			m_listenPort = listenPort;
 		} catch (BindException ex) {
 			listenPort++;
 			if(listenPort > port + MAX_NUMBER_OF_PORT_ATTEMPTS) {
 				return false;
 			}
 		} catch (IOException e) {
 			return false;
}
		}
		
		return foundOpenPort;
	}
 
/** keeping a few tests with mcast-port */
private static Connection getConnectionWithRandomMcastPort()
    throws SQLException {
  Properties props = new Properties();
  RETRY: while (true) {
    final int mcastPort = AvailablePort
        .getRandomAvailablePort(AvailablePort.JGROUPS);
    props.setProperty("mcast-port", String.valueOf(mcastPort));
    try {
      return getConnection(props);
    } catch (SQLException ex) {
      if ("XJ040".equals(ex.getSQLState())) {
        // check if a BindException then retry
        Throwable t = ex;
        while ((t = t.getCause()) != null) {
          if (t instanceof BindException) {
            continue RETRY;
          }
        }
      }
      throw ex;
    }
  }
}
 
源代码11 项目: rdf-delta   文件: Setup.java
@Override
public void restart() {
    server.stop();
    //testPort = LibX.choosePort();
    LocalServerConfig config = localServer.getConfig() ;
    LocalServer.release(localServer);
    localServer = LocalServer.create(config);
    resetDefaultHttpClient();
    DeltaLink localLink = DeltaLinkLocal.connect(localServer);
    server = DeltaServer.create(testPort, localLink);
    try {
        server.start();
    } catch (BindException e) {
        e.printStackTrace();
    }
    relink();
}
 
源代码12 项目: gama   文件: UDPConnector.java
public void openServerSocket(final IAgent agent) {
	final Integer port = Cast.asInt(agent.getScope(), this.getConfigurationParameter(SERVER_PORT));

	if (agent.getScope().getSimulation().getAttribute(_UDP_SERVER + port) == null) {
		try {
			final DatagramSocket sersock = new DatagramSocket(port);
			final MultiThreadedUDPSocketServer ssThread = new MultiThreadedUDPSocketServer(agent, sersock, this.getConfigurationParameter(PACKET_SIZE));
			ssThread.start();
			agent.getScope().getSimulation().setAttribute(_UDP_SERVER + port, ssThread);

		} catch (final BindException be) {
			throw GamaRuntimeException.create(be, agent.getScope());
		} catch (final Exception e) {
			throw GamaRuntimeException.create(e, agent.getScope());
		}
	}
}
 
源代码13 项目: j2objc   文件: NetworkBridge.java
public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException {
    if (address instanceof Inet6Address) {
        Inet6Address inet6Address = (Inet6Address) address;
        if (inet6Address.getScopeId() == 0 && inet6Address.isLinkLocalAddress()) {
            // Linux won't let you bind a link-local address without a scope id.
            // Find one.
            NetworkInterface nif = NetworkInterface.getByInetAddress(address);
            if (nif == null) {
                throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
            }
            try {
                address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
            } catch (UnknownHostException ex) {
                throw new AssertionError(ex); // Can't happen.
            }
        }
    }
    try {
        NetworkOs.bind(fd, address, port);
    } catch (ErrnoException errnoException) {
        throw new BindException(errnoException.getMessage(), errnoException);
    }
}
 
源代码14 项目: weex   文件: LocalSocketServer.java
@Nonnull
private static LocalServerSocket bindToSocket(String address) throws IOException {
  int retries = MAX_BIND_RETRIES;
  IOException firstException = null;
  do {
    try {
      if (LogUtil.isLoggable(Log.DEBUG)) {
        LogUtil.d("Trying to bind to @" + address);
      }
      return new LocalServerSocket(address);
    } catch (BindException be) {
      LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms...");
      if (firstException == null) {
        firstException = be;
      }
      Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS);
    }
  } while (retries-- > 0);

  throw firstException;
}
 
private synchronized int configureAndStartServer(String... ldifFiles) throws Exception {
    Collection<InMemoryListenerConfig> listenerConfigs = getInMemoryListenerConfigs();

    Schema schema = Schema.getDefaultStandardSchema();

    final String rootObjectDN = "o=TEST";
    InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(new DN(rootObjectDN));

    config.setSchema(schema);  //schema can be set on the rootDN too, per javadoc.
    config.setListenerConfigs(listenerConfigs);
    config.setEnforceAttributeSyntaxCompliance(false);
    config.setEnforceSingleStructuralObjectClass(false);

    //config.setLDAPDebugLogHandler(DEBUG_HANDLER);
    //config.setAccessLogHandler(DEBUG_HANDLER);
    //config.addAdditionalBindCredentials(configuration.getBindDn(), configuration.getPassword());

    server = new InMemoryDirectoryServer(config);

    try {
        /* Clear entries from server. */
        server.clear();
        server.startListening();
        return loadLdifFiles(ldifFiles);
    } catch (LDAPException ldape) {
        if (ldape.getMessage().contains("java.net.BindException")) {
            throw new BindException(ldape.getMessage());
        }
        throw ldape;
    }

}
 
源代码16 项目: logging-log4j2   文件: MockTcpSyslogServer.java
@Override
public void run() {
    System.out.println("TCP Server started");
    this.thread = Thread.currentThread();
    while (!shutdown) {
        try {
            final byte[] buffer = new byte[4096];
            Socket socket = null;
            try {
                socket = socketServer.accept();
                socket.setSoLinger(true, 0);
                final InputStream in = socket.getInputStream();
                int i = in.read(buffer, 0, buffer.length);
                while (i != -1) {
                    if (i < buffer.length) {
                        final String line = new String(buffer, 0, i);
                        messageList.add(line);
                        i = in.read(buffer, 0, buffer.length);
                    } else if (i == 0) {
                        System.out.println("No data received");
                    } else {
                        System.out.println("Message too long");
                    }
                }
            } catch (BindException be) {
                be.printStackTrace();
            } finally {
                if (socket != null) {
                    socket.close();
                }
            }
        } catch (final Exception ex) {
            if (!shutdown) {
                System.out.println("Caught exception: " + ex.getMessage());
            }
        }
    }
    System.out.println("TCP Server stopped");
}
 
源代码17 项目: jdk8u-jdk   文件: BadKdc.java
public static void go(String... expected)
        throws Exception {
    try {
        go0(expected);
    } catch (BindException be) {
        System.out.println("The random port is used by another process");
    } catch (LoginException le) {
        Throwable cause = le.getCause();
        if (cause instanceof Asn1Exception) {
            System.out.println("Bad packet possibly from another process");
            return;
        }
        throw le;
    }
}
 
源代码18 项目: cacheonix-core   文件: Receiver.java
/**
 * Creates a BindException with added information on the address for that the exception occurred. The stack trace of
 * the resulting exception is set to the stack trace of the original exception.
 *
 * @param originalException original exception.
 * @param endpoint          address
 * @return BindException with added information on the address for that the exception occurred.
 */
private static BindException createDetailedBindException(final BindException originalException,
        final InetSocketAddress endpoint) {

   final String newMessage = originalException.getMessage() + ". Address: " + endpoint;
   final BindException newBindException = new BindException(newMessage);
   newBindException.setStackTrace(originalException.getStackTrace());
   return newBindException;
}
 
源代码19 项目: openjdk-8-source   文件: Server.java
public static String start() throws Exception {
    int serverPort = 12345;
    ObjectName name = new ObjectName("test", "foo", "bar");
    MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    SteMBean bean = new Ste();
    jmxServer.registerMBean(bean, name);
    boolean exported = false;
    Random rnd = new Random(System.currentTimeMillis());
    do {
        try {
            LocateRegistry.createRegistry(serverPort);
            exported = true;
        } catch (ExportException ee) {
            if (ee.getCause() instanceof BindException) {
                serverPort = rnd.nextInt(10000) + 4096;
            } else {
                throw ee;
            }
        }

    } while (!exported);
    JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
    JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
    jmxConnector.start();

    return serverUrl.toString();
}
 
@Test
public void resolveMethodExceptionSubType() {
	AnnotationExceptionHandlerMethodResolver resolver = new AnnotationExceptionHandlerMethodResolver(ExceptionController.class);
	IOException ioException = new FileNotFoundException();
	assertEquals("handleIOException", resolver.resolveMethod(ioException).getName());
	SocketException bindException = new BindException();
	assertEquals("handleSocketException", resolver.resolveMethod(bindException).getName());
}
 
源代码21 项目: BigDataPlatform   文件: RestCtrlExceptionHandler.java
@ExceptionHandler(BindException.class)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public Result<Object> bindExceptionHandler(BindException e){
    String errorMsg="请求数据校验不合法: ";
    if(e!=null){
        errorMsg=e.getMessage();
        log.warn(errorMsg);
    }
    return new ResultUtil<>().setErrorMsg(errorMsg);
}
 
@Override
public void onSetUp() throws Exception {
	super.onSetUp();
	this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer());
	try {
		this.connectorServer.start();
	}
	catch (BindException ex) {
		System.out.println("Skipping remote JMX tests because binding to local port ["
				+ SERVICE_PORT + "] failed: " + ex.getMessage());
		runTests = false;
	}
}
 
@Test
public void resolveMethodExceptionSubType() {
	ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(ExceptionController.class);
	IOException ioException = new FileNotFoundException();
	assertEquals("handleIOException", resolver.resolveMethod(ioException).getName());
	SocketException bindException = new BindException();
	assertEquals("handleSocketException", resolver.resolveMethod(bindException).getName());
}
 
源代码24 项目: finalspeed   文件: FSServer.java
public static void main(String[] args) {
    try {
        FSServer fs = new FSServer();
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof BindException) {
            MLog.println("Udp port already in use.");
        }
        MLog.println("Start failed.");
        System.exit(0);
    }
}
 
源代码25 项目: big-c   文件: TestValidateConfigurationSettings.java
/**
 * Tests setting the rpc port to a different as the web port that an 
 * exception is NOT thrown 
 */
@Test(timeout = 300000)
public void testThatDifferentRPCandHttpPortsAreOK() 
    throws IOException {

  Configuration conf = new HdfsConfiguration();
  File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      nameDir.getAbsolutePath());

  Random rand = new Random();

  // A few retries in case the ports we choose are in use.
  for (int i = 0; i < 5; ++i) {
    final int port1 = 30000 + rand.nextInt(10000);
    final int port2 = port1 + 1 + rand.nextInt(10000);

    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port1);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port2);
    DFSTestUtil.formatNameNode(conf);
    NameNode nameNode = null;

    try {
      nameNode = new NameNode(conf); // should be OK!
      break;
    } catch(BindException be) {
      continue;     // Port in use? Try another.
    } finally {
      if (nameNode != null) {
        nameNode.stop();
      }
    }
  }
}
 
源代码26 项目: Flink-CEPplus   文件: BootstrapTools.java
/**
 * Starts an Actor System at a specific port.
 * @param configuration The Flink configuration.
 * @param actorSystemName Name of the started {@link ActorSystem}
 * @param listeningAddress The address to listen at.
 * @param listeningPort The port to listen at.
 * @param logger the logger to output log information.
 * @param actorSystemExecutorConfiguration configuration for the ActorSystem's underlying executor
 * @return The ActorSystem which has been started.
 * @throws Exception
 */
public static ActorSystem startActorSystem(
	Configuration configuration,
	String actorSystemName,
	String listeningAddress,
	int listeningPort,
	Logger logger,
	ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {

	String hostPortUrl = NetUtils.unresolvedHostAndPortToNormalizedString(listeningAddress, listeningPort);
	logger.info("Trying to start actor system at {}", hostPortUrl);

	try {
		Config akkaConfig = AkkaUtils.getAkkaConfig(
			configuration,
			new Some<>(new Tuple2<>(listeningAddress, listeningPort)),
			actorSystemExecutorConfiguration.getAkkaConfig());

		logger.debug("Using akka configuration\n {}", akkaConfig);

		ActorSystem actorSystem = AkkaUtils.createActorSystem(actorSystemName, akkaConfig);

		logger.info("Actor system started at {}", AkkaUtils.getAddress(actorSystem));
		return actorSystem;
	}
	catch (Throwable t) {
		if (t instanceof ChannelException) {
			Throwable cause = t.getCause();
			if (cause != null && t.getCause() instanceof BindException) {
				throw new IOException("Unable to create ActorSystem at address " + hostPortUrl +
					" : " + cause.getMessage(), t);
			}
		}
		throw new Exception("Could not create actor system", t);
	}
}
 
源代码27 项目: Flink-CEPplus   文件: BootstrapToolsTest.java
/**
 * Tests that the {@link ActorSystem} fails with an expressive exception if it cannot be
 * instantiated due to an occupied port.
 */
@Test
public void testActorSystemInstantiationFailureWhenPortOccupied() throws Exception {
	final ServerSocket portOccupier = new ServerSocket(0, 10, InetAddress.getByName("0.0.0.0"));

	try {
		final int port = portOccupier.getLocalPort();
		BootstrapTools.startActorSystem(new Configuration(), "0.0.0.0", port, LOG);
		fail("Expected to fail with a BindException");
	} catch (Exception e) {
		assertThat(ExceptionUtils.findThrowable(e, BindException.class).isPresent(), is(true));
	} finally {
		portOccupier.close();
	}
}
 
源代码28 项目: spider   文件: CommonSpider.java
@Autowired
public CommonSpider(TaskManager taskManager, StaticValue staticValue) throws InterruptedException, BindException {
    this.taskManager = taskManager;
    this.staticValue = staticValue;
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            deleteAll();
            LOG.debug("定时删除全部完成的普通网页抓取任务");
        }
    }, staticValue.getTaskDeleteDelay() * 3600000, staticValue.getTaskDeletePeriod() * 3600000);
    LOG.debug("定时删除普通网页抓取任务记录线程已启动,延时:{}小时,每{}小时删除一次", staticValue.getTaskDeleteDelay(), staticValue.getTaskDeletePeriod());
}
 
源代码29 项目: gemfirexd-oss   文件: Util.java
public static boolean treatAsBindException(SocketException se) {
  if(se instanceof BindException) {
    return true;
  }
  final String msg = se.getMessage();
  return (msg != null && msg.contains("Invalid argument: listen failed"));
}
 
源代码30 项目: jdk8u-jdk   文件: CloseServerSocket.java
private static void verifyPortInUse(int port) throws IOException {
    try {
        verifyPortFree(port);
    } catch (BindException e) {
        System.err.println("- port " + port + " is in use");
        return;
    }
}
 
 类所在包
 同包方法