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:gridool.communication.transport.tcp.GridThreadPerConnectionServer.java

public void start() throws GridException {
    if (listener == null) {
        throw new IllegalStateException("GridTransportListener is not set");
    }/*from  w ww  .  j ava  2  s.  com*/

    final int port = config.getTransportServerPort();
    final ServerSocket ss;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
    } catch (IOException e) {
        String errmsg = "Could not create ServerSocket on port: " + port;
        LOG.error(errmsg, e);
        throw new GridException(errmsg);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("GridThreadPerConnectionServer is started at port: " + port);
    }

    final int readers = config.getSelectorReadThreadsCount();
    final ExecutorService execPool = ExecutorFactory.newCachedThreadPool(readers, 60L,
            "GridThreadPerConnectionServer#RequestHandler", false);
    final int msgProcs = config.getMessageProcessorPoolSize();
    final ExecutorService msgProcPool = ExecutorFactory.newFixedThreadPool(msgProcs, "OioMessageProcessor",
            false);
    this.acceptor = new AcceptorThread(ss, listener, execPool, msgProcPool);

    acceptor.start();
}

From source file:com.netflix.hystrix.contrib.metrics.controller.HystricsMetricsControllerTest.java

@Override
protected Application configure() {
    int port = 0;
    try {/*from  w ww. ja  v a 2  s  . c  o m*/
        final ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();
    } catch (IOException e1) {
        throw new RuntimeException("Failed to find port to start test server");
    }
    set(TestProperties.CONTAINER_PORT, port);
    try {
        SystemConfiguration.setSystemProperties("test.properties");
    } catch (Exception e) {
        throw new RuntimeException("Failed to load config file");
    }
    return new ResourceConfig(HystricsMetricsControllerTest.class, HystrixStreamFeature.class);
}

From source file:org.apache.beam.sdk.io.jdbc.JdbcIOTest.java

@BeforeClass
public static void startDatabase() throws Exception {
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();//from w w  w  . ja  v  a 2 s. c om
    socket.close();

    LOG.info("Starting Derby database on {}", port);

    // by default, derby uses a lock timeout of 60 seconds. In order to speed up the test
    // and detect the lock faster, we decrease this timeout
    System.setProperty("derby.locks.waitTimeout", "2");
    System.setProperty("derby.stream.error.file", "target/derby.log");

    derbyServer = new NetworkServerControl(InetAddress.getByName("localhost"), port);
    StringWriter out = new StringWriter();
    derbyServer.start(new PrintWriter(out));
    boolean started = false;
    int count = 0;
    // Use two different methods to detect when server is started:
    // 1) Check the server stdout for the "started" string
    // 2) wait up to 15 seconds for the derby server to start based on a ping
    // on faster machines and networks, this may return very quick, but on slower
    // networks where the DNS lookups are slow, this may take a little time
    while (!started && count < 30) {
        if (out.toString().contains("started")) {
            started = true;
        } else {
            count++;
            Thread.sleep(500);
            try {
                derbyServer.ping();
                started = true;
            } catch (Throwable t) {
                // ignore, still trying to start
            }
        }
    }

    dataSource = new ClientDataSource();
    dataSource.setCreateDatabase("create");
    dataSource.setDatabaseName("target/beam");
    dataSource.setServerName("localhost");
    dataSource.setPortNumber(port);

    readTableName = DatabaseTestHelper.getTestTableName("UT_READ");

    DatabaseTestHelper.createTable(dataSource, readTableName);
    addInitialData(dataSource, readTableName);
}

From source file:ro.bmocanu.trafficproxy.input.InputConnectorServer.java

/**
 * {@inheritDoc}/*from w ww. ja v a 2  s . c  o m*/
 * 
 * @throws IOException
 */
@Override
public void init() throws IOException {
    serverSocket = new ServerSocket(connector.getPort());
    serverSocket.setSoTimeout(Constants.INPUT_CONNECTOR_SOCKET_TIMEOUT);
}

From source file:net.sf.jasperreports.phantomjs.InetUtil.java

public static int getAvailablePort() {
    try (ServerSocket socket = new ServerSocket(0)) {
        int port = socket.getLocalPort();
        if (log.isDebugEnabled()) {
            log.debug("found available port " + port);
        }/*from   w  ww. j a  v a2s.c o m*/
        return port;
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }

}

From source file:io.tilt.minka.domain.NetworkShardIDImpl.java

private void testPort() {
    ServerSocket socket = null;//from   ww  w.j  a va  2  s  . co  m
    try {
        socket = new ServerSocket(port);
        logger.info("{}: Testing host {} port {} OK", getClass().getSimpleName(), sourceHost, port);
    } catch (IOException e) {
        throw new IllegalArgumentException("Testing port cannot be opened: " + port, e);
    } finally {
        if (socket != null && !socket.isBound()) {
            throw new IllegalArgumentException("Testing port cannot be opened: " + port);
        } else if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new IllegalArgumentException("Testing port cannot be tested: " + port);
            }
        }
    }
}

From source file:org.apache.vysper.xmpp.extension.xep0124.inttests.IntegrationTestTemplate.java

private int findFreePort() throws IOException {
    ServerSocket ss = null;//from  ww  w.  j a v  a2s.c  om
    try {
        ss = new ServerSocket(0);
        ss.setReuseAddress(true);
        return ss.getLocalPort();
    } finally {
        if (ss != null) {
            ss.close();
        }
    }
}

From source file:com.joliciel.talismane.TalismaneServerImpl.java

@Override
public void process() {
    try {/*from ww w .  j  a  v a 2 s  . c o  m*/
        // ping the lexicon to load it
        TalismaneSession.getLexicon();
        LOG.debug("Starting server");

        ServerSocket serverSocket = new ServerSocket(port);
        while (listening) {
            TalismaneServerThread thread = new TalismaneServerThread(this, config, serverSocket.accept());
            thread.setTalismaneService(this.getTalismaneService());
            thread.start();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.apex.malhar.kafka.EmbeddedKafka.java

public void start() throws IOException {
    // Find port/*  ww w . j av  a  2 s. c  o m*/
    try {
        ServerSocket serverSocket = new ServerSocket(0);
        BROKERPORT = Integer.toString(serverSocket.getLocalPort());
        serverSocket.close();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // Setup Zookeeper
    zkServer = new EmbeddedZookeeper();
    String zkConnect = BROKERHOST + ":" + zkServer.port();
    zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$);
    zkUtils = ZkUtils.apply(zkClient, false);

    // Setup brokers
    cleanupDir();
    Properties props = new Properties();
    props.setProperty("zookeeper.connect", zkConnect);
    props.setProperty("broker.id", "0");
    props.setProperty("log.dirs", KAFKA_PATH);
    props.setProperty("listeners", "PLAINTEXT://" + BROKERHOST + ":" + BROKERPORT);
    KafkaConfig config = new KafkaConfig(props);
    Time mock = new MockTime();
    kafkaServer = TestUtils.createServer(config, mock);
}

From source file:com.streamsets.datacollector.http.TestLogServlet.java

private int getRandomPort() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    int port = ss.getLocalPort();
    ss.close();/* ww  w. j  a  v a 2s .co m*/
    return port;
}