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:com.twosigma.beakerx.kernel.MagicKernelManager.java

public static Integer findFreePort() {
    ServerSocket socket = null;//w  w  w .j  a va 2s . co m
    try {
        socket = new ServerSocket(0);
        socket.setReuseAddress(true);
        int port = socket.getLocalPort();
        try {
            socket.close();
        } catch (IOException e) {
        }
        return port;
    } catch (IOException e) {
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

From source file:de.undercouch.gradle.tasks.download.TestBase.java

/**
 * Find a free socket port//from   w  w w  .ja v  a2 s.c  om
 * @return the number of the free port
 * @throws IOException if an IO error occurred
 */
protected static int findPort() throws IOException {
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.zxy.commons.hystrix.HystrixProperties.java

/**
 * get hystrix stream port// w ww . java  2  s  . com
 * 
 * @return port
 * @throws IOException IOException
*/
public int getHystrixStreamPort() throws IOException {
    String portStr = env.getProperty(HYSTRIX_STREAM_PORT);
    if (StringUtils.isBlank(portStr)) {
        ServerSocket socket = new ServerSocket(0);
        try {
            return socket.getLocalPort();
        } finally {
            socket.close();
        }
    }
    return Integer.parseInt(portStr);
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * This method is the constructor./*from   w  ww .j av  a  2 s .  co m*/
 * @param job
 *        contains BSPJob configuration
 * @param processType
 *        the type of c++ process(for staff or workmanager)
 */
public Application(BSPJob job, String processType) throws IOException, InterruptedException {
    serverSocket = new ServerSocket(0);
    Map<String, String> env = new HashMap<String, String>();
    env.put("TMPDIR", System.getProperty("java.io.tmpdir"));
    env.put("bcbsp.pipes.command.port", Integer.toString(serverSocket.getLocalPort()));
    env.put("processType", processType);
    String bcbspdir = job.getConf().get("bcbsp.log.dir");
    LOG.info("bcbsp log dir : " + bcbspdir);
    env.put("bcbsp.log.dir", bcbspdir);
    List<String> cmd = new ArrayList<String>();
    String executable = job.getJobExe();
    FileUtil.chmod(executable, "a+x");
    cmd.add(executable);

    process = runClient(cmd, env);
    clientSocket = serverSocket.accept();
    this.handler = new TaskHandler();
    this.downlink = new BinaryProtocol(clientSocket, handler);
    this.downlink.start();
}

From source file:com.nike.vault.client.VaultClientTest.java

@Test(expected = VaultClientException.class)
public void read_throws_runtime_exception_if_unexpected_error_encountered() throws IOException {
    final ServerSocket serverSocket = new ServerSocket(0);
    final String vaultUrl = "http://localhost:" + serverSocket.getLocalPort();
    final VaultCredentialsProvider vaultCredentialsProvider = mock(VaultCredentialsProvider.class);
    final OkHttpClient httpClient = buildHttpClient(1, TimeUnit.SECONDS);
    vaultClient = new VaultClient(new StaticVaultUrlResolver(vaultUrl), vaultCredentialsProvider, httpClient);

    when(vaultCredentialsProvider.getCredentials()).thenReturn(new TestVaultCredentials());

    vaultClient.read("app/api-key");
}

From source file:com.kolich.boildown.Boil.java

private final void run() throws Exception {
    final Boiler.CompressionMethod method;
    final List<String> arguments;
    if (compress_ != null) {
        arguments = colonSplitter.splitToList(compress_);
        method = Boiler.CompressionMethod.COMPRESS;
    } else {/*w  ww  .jav  a  2s  .c o m*/
        arguments = colonSplitter.splitToList(decompress_);
        method = Boiler.CompressionMethod.DECOMPRESS;
    }

    if (arguments.size() != 3) {
        throw new IllegalArgumentException("Forwarder must be in the format of [port]:[host]:[port]");
    }

    // Parse the arguments.
    final int listenPort = Integer.parseInt(arguments.get(0));
    final String forwardHost = arguments.get(1);
    final int forwardPort = Integer.parseInt(arguments.get(2));

    final Boiler.Strategery strategery = getStrategery();

    final ThreadFactoryBuilder factoryBuilder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("boiler-%d (" + listenPort + ":" + forwardHost + ":" + forwardPort + ")");

    final ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(poolSize_,
            factoryBuilder.build());

    try (final ServerSocket listener = new ServerSocket(listenPort)) {
        // Run loop!
        while (true) {
            // Blocks, waiting for new connections.
            final Socket client = listener.accept();
            if (threadPool.getActiveCount() >= poolSize_) {
                // All boilers busy, forcibly hang up.
                IOUtils.closeQuietly(client);
            } else {
                // Submit the boiler to the pool, only if there's space to safely do so.
                threadPool
                        .submit(new Boiler(client, method, strategery, forwardHost, forwardPort, bufferSize_));
            }
        }
    } catch (Exception e) {
        log.error("Exception in main run-loop.", e);
    } finally {
        threadPool.shutdown();
    }
}

From source file:com.evolveum.midpoint.model.intest.TestNotifications.java

private int findFreePort() throws IOException {
    try (ServerSocket socket = new ServerSocket(0)) {
        socket.setReuseAddress(true);//  w ww.  j  a  v a2s .  co m
        return socket.getLocalPort();
    }
}

From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java

@Override
public void run() {
    try {/* www . j av  a2  s  .c o m*/
        serverSocket_ = new ServerSocket(port_);
        started_.set(true);
        LOG.info("Starting listening on port " + port_);
        while (!shutdown_) {
            final Socket s = serverSocket_.accept();
            final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            final CharBuffer cb = CharBuffer.allocate(5000);
            br.read(cb);
            cb.flip();
            final String in = cb.toString();
            cb.rewind();

            final RawResponseData responseData = getResponseData(in);

            if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) {
                LOG.info("Closing impolitely in & output streams");
                s.getOutputStream().close();
            } else {
                final PrintWriter pw = new PrintWriter(s.getOutputStream());
                pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage());
                for (final NameValuePair header : responseData.getHeaders()) {
                    pw.println(header.getName() + ": " + header.getValue());
                }
                pw.println();
                pw.println(responseData.getStringContent());
                pw.println();
                pw.flush();
                pw.close();
            }
            br.close();
            s.close();
        }
    } catch (final SocketException e) {
        if (!shutdown_) {
            LOG.error(e);
        }
    } catch (final IOException e) {
        LOG.error(e);
    } finally {
        LOG.info("Finished listening on port " + port_);
    }
}

From source file:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private int detectPort() throws IOException {
    final ServerSocket socket = new ServerSocket(0);
    try {//from ww  w.java 2  s .c  o  m
        return socket.getLocalPort();
    } finally {
        socket.close();
    }
}

From source file:any.Linker.java

public void serve(final int port) {
    logger.info("+SERVICE: started to serve");

    try {/*  w  ww. j a  v  a  2 s .co m*/
        // Start the server socket (?)
        serverSocket = new ServerSocket(port);

        while (true) {
            final Socket socket = serverSocket.accept();
            logger.info(
                    socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort() + " is connected");

            IConnection conn = new Connection(Thread.currentThread().getName(), this, socket);
            namedCon.put(socket.getInetAddress().getCanonicalHostName() + ":" + socket.getPort(), conn);
            // namedCon.put( "host", conn);
            logger.info("+SERVICE: connected to client " + socket.getInetAddress().getCanonicalHostName() + ":"
                    + socket.getPort());
        }
    } catch (IOException e) {
        logger.error("+SERVICE, serve IO exception", e);
    } catch (InterruptedException e) {
        logger.error("+SERVICE, main loop interupted", e);
    }
}