本文整理匯總了Java中java.net.BindException類的典型用法代碼示例。如果您正苦於以下問題:Java BindException類的具體用法?Java BindException怎麽用?Java BindException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
BindException類屬於java.net包,在下文中一共展示了BindException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testBindError
import java.net.BindException; //導入依賴的package包/類
@Test
public void testBindError() throws Exception {
Configuration conf = new Configuration();
ServerSocket socket = new ServerSocket();
InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
socket.bind(address);
try {
int min = socket.getLocalPort();
conf.set("TestRange", min+"-"+min);
ServerSocket socket2 = new ServerSocket();
InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
boolean caught = false;
try {
Server.bind(socket2, address2, 10, conf, "TestRange");
} catch (BindException e) {
caught = true;
} finally {
socket2.close();
}
assertTrue("Failed to catch the expected bind exception",caught);
} finally {
socket.close();
}
}
示例2: InternalWebServer
import java.net.BindException; //導入依賴的package包/類
/**
* Build a new instance of InternalWebServer
* @param nonce
* A string to verify in responses
* @throws IOException
* In case of Exception when starting webserver
*/
public InternalWebServer(UUID nonce) throws IOException {
this.listenPort = Integer.parseInt(OwaNotifier.getInstance().getProps().getProperty("listenPort", "8080"));
this.nonce = nonce;
// Search an available port
while(this.socket == null) {
try {
InetAddress[] IP=InetAddress.getAllByName("localhost");
if(IP.length < 1) {
throw new IOException("Unable to find localhost ip");
}
this.socket = new ServerSocket(this.listenPort, 10, IP[0]); // Start, listen on port 8080
logger.info("Use listen " + this.socket.getInetAddress().toString() + ":" + this.listenPort);
} catch (BindException e){
this.listenPort = this.listenPort +1;
OwaNotifier.getInstance().setProps("listenPort", this.listenPort + "");
}
}
// detach thread
serverThread = new Thread(this);
serverThread.start();
}
示例3: TestWebServer
import java.net.BindException; //導入依賴的package包/類
public TestWebServer() throws IOException {
int port = 9000;
boolean bound = false;
do {
try {
httpServer.bind(new InetSocketAddress(port), 0);
bound = true;
} catch (BindException e) {
port++;
}
} while (!bound && port < 12000);
httpServer.createContext(ECHO_ENDPOINT, new EchoHandler());
httpServer.start();
}
示例4: createServerSocket
import java.net.BindException; //導入依賴的package包/類
public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
List<GatewayTransportFilter> transportFilters, int socketBufferSize) throws IOException {
if (transportFilters.isEmpty()) {
return createServerSocket(nport, backlog, bindAddr, socketBufferSize);
} else {
printConfig();
ServerSocket result = new TransportFilterServerSocket(transportFilters);
result.setReuseAddress(true);
// Set the receive buffer size before binding the socket so
// that large buffers will be allocated on accepted sockets (see
// java.net.ServerSocket.setReceiverBufferSize javadocs)
result.setReceiveBufferSize(socketBufferSize);
try {
result.bind(new InetSocketAddress(bindAddr, nport), backlog);
} catch (BindException e) {
BindException throwMe =
new BindException(LocalizedStrings.SocketCreator_FAILED_TO_CREATE_SERVER_SOCKET_ON_0_1
.toLocalizedString(new Object[] {bindAddr, Integer.valueOf(nport)}));
throwMe.initCause(e);
throw throwMe;
}
return result;
}
}
示例5: testThatMatchingRPCandHttpPortsThrowException
import java.net.BindException; //導入依賴的package包/類
/**
* Tests setting the rpc port to the same as the web port to test that
* an exception
* is thrown when trying to re-use the same port
*/
@Test(expected = BindException.class, timeout = 300000)
public void testThatMatchingRPCandHttpPortsThrowException()
throws IOException {
NameNode nameNode = null;
try {
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();
final int port = 30000 + rand.nextInt(30000);
// set both of these to the same port. It should fail.
FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port);
conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port);
DFSTestUtil.formatNameNode(conf);
nameNode = new NameNode(conf);
} finally {
if (nameNode != null) {
nameNode.stop();
}
}
}
示例6: testConfigurationKo
import java.net.BindException; //導入依賴的package包/類
/**
* 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;
}
示例7: testConfigurationFile
import java.net.BindException; //導入依賴的package包/類
/**
* 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";
}
示例8: testAgentRemote
import java.net.BindException; //導入依賴的package包/類
@Test
public final void testAgentRemote() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
String status = jcmd.status();
assertStatusMatches(REMOTE_AGENT_STATUS, status);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
示例9: testRemoteEnabled
import java.net.BindException; //導入依賴的package包/類
/**
* After enabling the remote agent the 'sun.management.JMXConnectorServer.remote.enabled'
* counter will be exported with value of '0' - corresponding to the actual
* version of the associated remote connector perf counters.
* @throws Exception
*/
@Test
public void testRemoteEnabled() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
String v = getCounters().getProperty(REMOTE_STATUS_KEY);
assertNotNull(v);
assertEquals("0", v);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
示例10: testRemoteDisabled
import java.net.BindException; //導入依賴的package包/類
/**
* After disabling the remote agent the value of 'sun.management.JMXConnectorServer.remote.enabled'
* counter will become '-1'.
* @throws Exception
*/
@Test
public void testRemoteDisabled() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
jcmd.stop();
String v = getCounters().getProperty(REMOTE_STATUS_KEY);
assertNotNull(v);
assertEquals("-1", v);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
示例11: bind
import java.net.BindException; //導入依賴的package包/類
public int bind(final int initialPort, boolean allowPortHunting) {
int port = initialPort - 1;
while (true) {
try {
allChannels.add(b.bind(++port).sync().channel());
break;
} catch (Exception e) {
// TODO(DRILL-3026): Revisit: Exception is not (always) BindException.
// One case is "java.io.IOException: bind() failed: Address already in
// use".
if (e instanceof BindException && allowPortHunting) {
continue;
}
throw UserException.resourceError( e )
.addContext( "Server", rpcConfig.getName())
.message( "Could not bind to port %s.", port )
.build(logger);
}
}
connect = !connect;
logger.info("[{}]: Server started on port {}.", rpcConfig.getName(), port);
return port;
}
示例12: RequestListenerThread
import java.net.BindException; //導入依賴的package包/類
public RequestListenerThread(Context context) throws IOException, BindException {
serversocket = new ServerSocket(PORT);
params = new BasicHttpParams();
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
httpProcessor.addInterceptor(new ResponseDate());
httpProcessor.addInterceptor(new ResponseServer());
httpProcessor.addInterceptor(new ResponseContent());
httpProcessor.addInterceptor(new ResponseConnControl());
// Set up the HTTP service
this.httpService = new YaaccHttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), context);
}
示例13: bindNIOServerSocket
import java.net.BindException; //導入依賴的package包/類
/**
* Creates a NIO ServerSocketChannel, and gets the ServerSocket from
* there. Then binds the obtained socket.
* This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
* IPv6 address. Works on Oracle JDK 1.7.
*/
private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
while (true) {
int port = HBaseTestingUtility.randomFreePort();
InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
ServerSocketChannel channel = null;
ServerSocket serverSocket = null;
try {
channel = ServerSocketChannel.open();
serverSocket = channel.socket();
serverSocket.bind(addr); // This does not work
break;
} catch (BindException ex) {
//continue
} finally {
if (serverSocket != null) {
serverSocket.close();
}
if (channel != null) {
channel.close();
}
}
}
}
示例14: testServerSocket
import java.net.BindException; //導入依賴的package包/類
/**
* Checks whether we are effected by the JDK issue on windows, and if so
* ensures that we are running with preferIPv4Stack=true.
*/
@Test
public void testServerSocket() throws IOException {
byte[] addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
InetAddress inetAddr = InetAddress.getByAddress(addr);
try {
bindServerSocket(inetAddr);
bindNIOServerSocket(inetAddr);
//if on *nix or windows JDK7, both will pass
} catch(java.net.SocketException ex) {
//On Windows JDK6, we will get expected exception:
//java.net.SocketException: Address family not supported by protocol family
//or java.net.SocketException: Protocol family not supported
Assert.assertFalse(ex.getClass().isInstance(BindException.class));
Assert.assertTrue(ex.getMessage().toLowerCase().contains("protocol family"));
LOG.info("Received expected exception:");
LOG.info(ex);
//if this is the case, ensure that we are running on preferIPv4=true
ensurePreferIPv4();
}
}
示例15: putHiddenServicePortInstance
import java.net.BindException; //導入依賴的package包/類
/**
* Assign a HiddenServicePortInstance to a port.
*
* @param instance
* instance inclusive port number
* @throws BindException
* if the port is already in use
*/
public synchronized void putHiddenServicePortInstance(
HiddenServicePortInstance instance) throws BindException
{
// check that port is still available
final int port = instance.getPort();
final HiddenServicePortInstance old = getHiddenServicePortInstance(port);
if (old != null && old.isOpen())
{
// port is already occupied
throw new BindException("port=" + port
+ " is already in use - instance=" + instance
+ " cannot be bound to");
}
// reserve the port
listenPortsOfThisHiddenService.put(port, instance);
instance.setHiddenServiceInstance(this);
}