Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

In this page you can find the example usage for java.net ServerSocket ServerSocket.

Prototype

public ServerSocket(int port) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:org.Cherry.Modules.Web.Engine.WebEngine.java

public ServerSocket getServerSocket() {
    if (null == _serverSocket) {
        try {/*from  ww w.  j av  a  2s  .c o  m*/
            _serverSocket = new ServerSocket(getPort());
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        }

        info("Listening on port [{}]", _serverSocket.getLocalPort());
    }

    return _serverSocket;
}

From source file:com.github.podd.resources.test.AbstractResourceImplTest.java

private static synchronized int getFreePort() {
    int result = -1;
    while (result <= 0) {
        // Avoid infinite loops when the majority of legitimate ports have been tried already
        // and the test suite is too big or broken somehow.
        Assert.assertTrue("No free ports left for parallel tests",
                AbstractResourceImplTest.usedPorts.size() < 50000);
        try (ServerSocket ss = new ServerSocket(0)) {
            ss.setReuseAddress(true);// ww  w.j  a  v  a2s.c  om
            result = ss.getLocalPort();
            if (AbstractResourceImplTest.usedPorts.contains(result)) {
                result = -1;
            } else {
                // If the next port was already in used ports then the following will return
                // false and we will set result to -1
                if (AbstractResourceImplTest.usedPorts.add(result)) {
                    try (DatagramSocket ds = new DatagramSocket(result);) {
                        ds.setReuseAddress(true);
                    }
                } else {
                    result = -1;
                }
            }
        } catch (final IOException e) {
            result = -1;
        }
    }
    return result;
}

From source file:RedPenRunner.java

private static boolean isPortTaken(int portNum) {
    boolean portTaken = false;
    try (ServerSocket socket = new ServerSocket(portNum)) {
        // do nothing
    } catch (IOException e) {
        System.err.println("Detect: port is taken"); // TODO: use logger
        portTaken = true;/*  w  w w.j  a  v  a2 s  .co  m*/
    }
    return portTaken;
}

From source file:com.subgraph.vega.internal.http.proxy.HttpProxy.java

@Override
public void startProxy() {
    try {/*from ww  w  . ja v a 2  s .c  o  m*/
        logger.info("Listening on port " + listenPort);
        serverSocket = new ServerSocket(listenPort);
        proxyThread = new Thread(createProxyLoopRunnable());
        proxyThread.start();
    } catch (IOException e) {
        logger.log(Level.WARNING, "IO error creating listening socket: " + e.getMessage(), e);
    }
}

From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java

protected int getLocalPort() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    int ret = ss.getLocalPort();
    ss.close();/*from   ww  w  .  j a va  2s .  c o m*/
    return ret;
}

From source file:org.apache.htrace.impl.HTracedProcess.java

private HTracedProcess(Builder builder) throws Exception {
    this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile();
    if (!this.htracedPath.exists()) {
        throw new RuntimeException("No htraced binary exists at " + this.htracedPath);
    }/*  w ww .j  a va 2s.  c o  m*/
    this.dataDir = new DataDir();
    // Create a notifier socket bound to a random port.
    ServerSocket listener = new ServerSocket(0);
    boolean success = false;
    Process process = null;
    HttpClient http = null;
    try {
        // Use a random port for the web address.  No 'scheme' yet.
        String random = builder.host + ":0";
        String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath();
        // Pass cmdline args to htraced to it uses our test dir for data.
        ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE",
                "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random,
                "-Ddata.store.clear=true",
                "-Dstartup.notification.address=localhost:" + listener.getLocalPort(),
                "-Ddata.store.directories=" + dataDir.get().getAbsolutePath());

        // Set HTRACED_CONF_DIR to the temporary directory we just created, to
        // ensure that it doesn't pull in any other configuration file that might
        // be on this test machine.
        Map<String, String> env = pb.environment();
        env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath());

        // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that
        // we use the default value (which finds the local web files by relative
        // path).
        env.remove("HTRACED_WEB_DIR");

        pb.redirectErrorStream(true);
        // Inherit STDERR/STDOUT i/o; dumps on console for now.  Can add logs later.
        pb.inheritIO();
        pb.directory(dataDir.get());
        //assert pb.redirectInput() == Redirect.PIPE;
        //assert pb.redirectOutput().file() == dataDir;
        process = pb.start();
        assert process.getInputStream().read() == -1;
        StartupNotificationData data = readStartupNotification(listener);
        httpAddr = data.httpAddr;
        hrpcAddr = data.hrpcAddr;
        LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr
                + ", logging to " + logPath);
        http = RestBufferManager.createHttpClient(60000L, 60000L);
        http.start();
        success = true;
    } finally {
        if (!success) {
            // Clean up after failure
            if (process != null) {
                process.destroy();
                process = null;
            }
            if (http != null) {
                http.stop();
            }
        }
        delegate = process;
        listener.close();
        httpClient = http;
    }
}

From source file:org.alexlg.bankit.Launcher.java

/**
 * Check if a tcp port is open on localhost interface.
 * @param port Port to check/*w ww  .  j av a 2  s  .  co  m*/
 * @return True if port is open, false otherwise
 */
private static boolean isPortOpen(int port) {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(port);
        socket.setReuseAddress(true);
    } catch (IOException e) {
        return false;
    } finally {
        // Clean up
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
        }
    }

    return true;
}

From source file:org.ngrinder.perftest.service.ConsoleManagerTest.java

@Test
public void testAvailableSocket() throws IOException {
    ServerSocket serverSocket = null;
    try {// w  w w  . j a va 2 s.c o m
        // When port is already used
        serverSocket = new ServerSocket(20111);
        int localPort = serverSocket.getLocalPort();

        // It should be excluded in available ports
        List<Integer> availablePorts = NetworkUtils.getAvailablePorts("", 20, 20111, 40000);
        assertThat(availablePorts.contains(localPort), not(true));
        assertThat(availablePorts.size(), is(20));
    } finally {
        if (serverSocket != null) {
            serverSocket.close();
        }
    }
}

From source file:com.ning.metrics.goodwill.access.CachingGoodwillAccessorTest.java

private int findFreePort() throws IOException {
    ServerSocket socket = null;//from w w w. ja  va 2 s  .co  m

    try {
        socket = new ServerSocket(0);

        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test get connection url proxy with proxy.
 * //from   w  w  w . j a  va  2s .co m
 *
 * @throws Exception the exception
 */
public void testGetConnectionURLProxyWithProxy() throws Exception {
    final ServerSocket socket = new ServerSocket(PROXY_PORT);
    Thread thread = new Thread("ProxySocketAcceptThread") {
        @Override
        public void run() {
            try {
                while (!bStop) {
                    Socket sock = socket.accept();
                    Log.debug("Accepted connection, sending back garbage and close socket...");
                    sock.getOutputStream().write(1);
                    sock.close();
                }
            } catch (IOException e) {
                Log.error(e);
            }
        }
    };
    thread.setDaemon(true); // to finish tests even if this is still running
    thread.start();
    Log.debug("Using local port: " + socket.getLocalPort());
    try {
        // useful content when inet access is allowed
        Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
        HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL),
                new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password"));
        assertNotNull(connection);
        connection.disconnect();
    } finally {
        bStop = true;
        socket.close();
        thread.join();
    }
}