Java Code Examples for java.net.ServerSocket#close()

The following examples show how to use java.net.ServerSocket#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MoviesHtmlUnitTest.java    From tomee with Apache License 2.0 8 votes vote down vote up
@BeforeClass
public static void start() throws IOException {

    // get a random unused port to use for http requests
    ServerSocket server = new ServerSocket(0);
    port = server.getLocalPort();
    server.close();

    webApp = createWebApp();
    Properties p = new Properties();
    p.setProperty(EJBContainer.APP_NAME, "moviefun");
    p.setProperty(EJBContainer.PROVIDER, "tomee-embedded"); // need web feature
    p.setProperty(EJBContainer.MODULES, webApp.getAbsolutePath());
    p.setProperty(EmbeddedTomEEContainer.TOMEE_EJBCONTAINER_HTTP_PORT, String.valueOf(port));
    container = EJBContainer.createEJBContainer(p);
}
 
Example 2
Source File: NoLaunchOptionTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // find a free port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    ss.close();
    String address = String.valueOf(port);

    String javaExe = System.getProperty("java.home") +
        java.io.File.separator + "bin" +
        java.io.File.separator + "java";
    String targetClass = "NotAClass";
    String cmds [] = {javaExe,
                      "-agentlib:jdwp=transport=dt_socket,address=" +
                      address + "," +
                      "onthrow=java.lang.ClassNotFoundException,suspend=n",
                      targetClass};
    NoLaunchOptionTest myTest = new NoLaunchOptionTest();
    String results [] = myTest.run(VMConnection.insertDebuggeeVMOptions(cmds));
    if ((results[RETSTAT].equals("1")) &&
        (results[STDERR].contains("ERROR:"))) {
        System.out.println("Test passed: status = 1 with warning messages " +
                           "is expected and normal for this test");
    } else {
        throw new Exception("Test failed: unspecified test failure");
    }
}
 
Example 3
Source File: NoLaunchOptionTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // find a free port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    ss.close();
    String address = String.valueOf(port);

    String javaExe = System.getProperty("java.home") +
        java.io.File.separator + "bin" +
        java.io.File.separator + "java";
    String targetClass = "NotAClass";
    String cmds [] = {javaExe,
                      "-agentlib:jdwp=transport=dt_socket,address=" +
                      address + "," +
                      "onthrow=java.lang.ClassNotFoundException,suspend=n",
                      targetClass};
    NoLaunchOptionTest myTest = new NoLaunchOptionTest();
    String results [] = myTest.run(VMConnection.insertDebuggeeVMOptions(cmds));
    if ((results[RETSTAT].equals("1")) &&
        (results[STDERR].contains("ERROR:"))) {
        System.out.println("Test passed: status = 1 with warning messages " +
                           "is expected and normal for this test");
    } else {
        throw new Exception("Test failed: unspecified test failure");
    }
}
 
Example 4
Source File: AvailablePortJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testIsPortAvailable() throws IOException {
  ServerSocket socket = new ServerSocket();
  int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
  socket.bind(new InetSocketAddress(InetAddressUtil.LOOPBACK,  port));
  try {
   Assert.assertFalse(AvailablePort.isPortAvailable(port,
        AvailablePort.SOCKET,
        InetAddress.getByName(InetAddressUtil.LOOPBACK_ADDRESS)));
    //Get local host will return the hostname for the server, so this should succeed, since we're bound to the loopback address only.
    Assert.assertTrue(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET, InetAddress.getLocalHost()));
    //This should test all interfaces.
    Assert.assertFalse(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET));
  } finally {
    socket.close();
  }
}
 
Example 5
Source File: CCKafkaTestUtils.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Find a local port.
 * @return A local port to use.
 */
public static int findLocalPort() {
  int port = -1;
  while (port < 0) {
    try {
      ServerSocket socket = new ServerSocket(0);
      socket.setReuseAddress(true);
      port = socket.getLocalPort();
      try {
        socket.close();
      } catch (IOException e) {
        // Ignore IOException on close()
      }
    } catch (IOException ie) {
      // let it go.
    }
  }
  return port;
}
 
Example 6
Source File: Application.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    // bind to a random port
    if (args.length < 1) {
        System.err.println("First argument should be path to output file.");
    }
    String outFileName = args[0];

    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    int pid = ProcessTools.getProcessId();

    System.out.println("shutdownPort=" + port);
    System.out.println("pid=" + pid);
    System.out.flush();

    try (PrintWriter writer = new PrintWriter(outFileName)) {
        writer.println("shutdownPort=" + port);
        writer.println("pid=" + pid);
        writer.println("done");
        writer.flush();
    }

    // wait for test harness to connect
    Socket s = ss.accept();
    s.close();
    ss.close();
}
 
Example 7
Source File: ServerSocketWrapper.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Closes the underlying socket.
 */
public void close()
  throws IOException
{
  ServerSocket ss = _ss;
  _ss = ss;

  if (ss != null) {
    try {
      ss.close();
    } catch (Exception e) {
    }
  }
}
 
Example 8
Source File: Utils.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Picks a port that is not used right at this moment.
 * Warning: Not thread safe. May see "BindException: Address already in use: bind" if using the
 * returned port to create a new server socket when other threads/processes are concurrently
 * creating new sockets without a specific port.
 */
public static int pickUnusedPort() {
  try {
    ServerSocket serverSocket = new ServerSocket(0);
    int port = serverSocket.getLocalPort();
    serverSocket.close();
    return port;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 9
Source File: JedisIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
    
    // Take an available port
    ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();
    
    redisServer = new RedisServer(port);
    redisServer.start();
    
    // Configure JEDIS
    jedis = new Jedis("localhost", port);
}
 
Example 10
Source File: AcceptCauseFileDescriptorLeak.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ServerSocket ss = new ServerSocket(0) {
        public Socket accept() throws IOException {
            Socket s = new Socket() { };
            s.setSoTimeout(10000);
            implAccept(s);
            return s;
        }
    };
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                for (int i = 0; i < REPS; i++) {
                    (new Socket("localhost", ss.getLocalPort())).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    for (int i = 0; i < REPS; i++) {
        ss.accept().close();
    }
    ss.close();
    t.join();
}
 
Example 11
Source File: BootstrapToolsTest.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example 12
Source File: NetUtil.java    From vjtools with Apache License 2.0 5 votes vote down vote up
/**
 * 测试端口是否空闲可用, from Spring SocketUtils
 */
public static boolean isPortAvailable(int port) {
	try {
		ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
				InetAddress.getByName("localhost"));
		serverSocket.close();
		return true;
	} catch (Exception ex) { // NOSONAR
		return false;
	}
}
 
Example 13
Source File: SocketTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static void closeQuietly(final ServerSocket socket) {
    if (null != socket) {
        try {
            socket.close();
        } catch (final IOException ignore) {
        }
    }
}
 
Example 14
Source File: SocketUtilsTest.java    From JavaLinuxNet with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerSocketFd() throws Exception {
    //create Server socket and get access to fd
    ServerSocket s= ServerSocketFactory.getDefault().createServerSocket();
    int fd=SocketUtils.getFd(s);
    log.info("fd server socket: {}",fd);
    Assert.assertTrue("FD must be > 0", fd > 0);
    s.close();
}
 
Example 15
Source File: InvalidLdapFilters.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    ServerSocket serverSock = new ServerSocket(serverPort);

    // signal client, it's ready to accecpt connection
    serverPort = serverSock.getLocalPort();
    serverReady = true;

    // accept a connection
    Socket socket = serverSock.accept();
    System.out.println("Server: Connection accepted");

    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    // read the bindRequest
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
        break;
    }

    byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
                           0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
    // write bindResponse
    os.write(bindResponse);
    os.flush();

    // ignore any more request.
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
    }

    is.close();
    os.close();
    socket.close();
    serverSock.close();
}
 
Example 16
Source File: ExclusiveBind.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    // find a free port
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    ss.close();

    String address = String.valueOf(port);

    // launch the first debuggee
    ProcessBuilder process1 = prepareLauncher(address, true, "HelloWorld");
    // start the debuggee and wait for the "ready" message
    Process p = ProcessTools.startProcess(
            "process1",
            process1,
            line -> line.equals("Listening for transport dt_socket at address: " + address),
            Math.round(5000 * Utils.TIMEOUT_FACTOR),
            TimeUnit.MILLISECONDS
    );

    // launch a second debuggee with the same address
    ProcessBuilder process2 = prepareLauncher(address, false, "HelloWorld");

    // get exit status from second debuggee
    int exitCode = ProcessTools.startProcess("process2", process2).waitFor();

    // clean-up - attach to first debuggee and resume it
    AttachingConnector conn = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach");
    Map conn_args = conn.defaultArguments();
    Connector.IntegerArgument port_arg =
        (Connector.IntegerArgument)conn_args.get("port");
    port_arg.setValue(port);
    VirtualMachine vm = conn.attach(conn_args);
    vm.resume();

    // if the second debuggee ran to completion then we've got a problem
    if (exitCode == 0) {
        throw new RuntimeException("Test failed - second debuggee didn't fail to bind");
    } else {
        System.out.println("Test passed - second debuggee correctly failed to bind");
    }
}
 
Example 17
Source File: RabbitTestSupport.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 4 votes vote down vote up
public RabbitProxy() throws IOException {
	ServerSocket serverSocket = ServerSocketFactory.getDefault()
			.createServerSocket(0);
	this.port = serverSocket.getLocalPort();
	serverSocket.close();
}
 
Example 18
Source File: AuthenticatorTestCase.java    From big-c with Apache License 2.0 4 votes vote down vote up
protected int getLocalPort() throws Exception {
  ServerSocket ss = new ServerSocket(0);
  int ret = ss.getLocalPort();
  ss.close();
  return ret;
}
 
Example 19
Source File: IsKeepingAlive.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        ServerSocket ss = new ServerSocket(0);

        SecurityManager security = System.getSecurityManager();
        if (security == null) {
            security = new SecurityManager();
            System.setSecurityManager(security);
        }

        URL url1 = new URL("http://localhost:" + ss.getLocalPort());

        HttpClient c1 = HttpClient.New(url1);

        boolean keepAlive = c1.isKeepingAlive();

        ss.close();
    }
 
Example 20
Source File: IOUtils.java    From AndroidBase with Apache License 2.0 3 votes vote down vote up
/**
 * Unconditionally close a <code>ServerSocket</code>.
 * <p/>
 * Equivalent to {@link ServerSocket#close()}, except any exceptions will be ignored.
 * This is typically used in finally blocks.
 * <p/>
 * Example code:
 * <pre>
 *   ServerSocket socket = null;
 *   try {
 *       socket = new ServerSocket();
 *       // process socket
 *       socket.close();
 *   } catch (Exception e) {
 *       // error handling
 *   } finally {
 *       IOUtils.closeQuietly(socket);
 *   }
 * </pre>
 *
 * @param sock the ServerSocket to close, may be null or already closed
 * @since 2.2
 */
public static void closeQuietly(ServerSocket sock) {
    if (sock != null) {
        try {
            sock.close();
        } catch (IOException ioe) {
            // ignored
        }
    }
}