Example usage for java.net ServerSocket getLocalPort

List of usage examples for java.net ServerSocket getLocalPort

Introduction

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

Prototype

public int getLocalPort() 

Source Link

Document

Returns the port number on which this socket is listening.

Usage

From source file:org.docwhat.iated.AppState.java

/** Find a free TCP port.
 *
 * From:/*from www . j  a  v a 2  s .  co m*/
 * http://stackoverflow.com/questions/2675362/how-to-find-an-available-port
 * http://stackoverflow.com/questions/3265825/finding-two-free-tcp-ports
 *
 * @return A free socket number.
 * @throws IOException If not free port can be found.
 */
public int findFreePort() throws IOException {
    ServerSocket socket = null;

    try {
        socket = new ServerSocket(0);
        return socket.getLocalPort();
    } catch (Exception e) {
        throw new IOException("no free port found");
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.lib.OpflexConnectionServiceTest.java

private int getAvailableServerPort() {
    try {/*w  w  w.j a  v  a  2s  . co  m*/
        int freePort;
        ServerSocket s = create(new int[] { 6670, 6671, 6672, 6673, 6674, 6675, 6676, 6677, 6678 });
        freePort = s.getLocalPort();
        s.close();
        return freePort;
    } catch (IOException ex) {
        return 0;
    }
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSink() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override/*from  w  ww  . j a v  a  2 s .com*/
        public void run() {
            try {
                SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0);
                simpleSink.open(new Configuration());
                simpleSink.invoke(TEST_MESSAGE + '\n');
                simpleSink.close();
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));

    String value = rdr.readLine();

    sinkRunner.join();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}

From source file:org.wso2.developerstudio.eclipse.embedded.tomcat.server.EmbeddedTomcatServer.java

/**
 * Finds a port which is currently not in use.
 * /*ww w.j  a  v a 2s .co  m*/
 * @return Available Port.
 * 
 * @throws IOException
 */
private Integer getAvailablePort() throws IOException {
    ServerSocket socket = new ServerSocket(0);
    Integer port = socket.getLocalPort();
    socket.close();
    return port;
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSinkAutoFlush() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    final SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true);
    simpleSink.open(new Configuration());

    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    Thread sinkRunner = new Thread("Test sink runner") {
        @Override//from w  w  w  .  j  av  a 2 s.  c o  m
        public void run() {
            try {
                // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
                simpleSink.invoke(TEST_MESSAGE + '\n');
            } catch (Throwable t) {
                error.set(t);
            }
        }
    };

    sinkRunner.start();

    Socket sk = server.accept();
    BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream()));
    String value = rdr.readLine();

    sinkRunner.join();
    simpleSink.close();
    server.close();

    if (error.get() != null) {
        Throwable t = error.get();
        t.printStackTrace();
        fail("Error in spawned thread: " + t.getMessage());
    }

    assertEquals(TEST_MESSAGE, value);
}

From source file:uk.ac.horizon.ubihelper.j2se.Server.java

public void init(InetAddress address, int port) {
    protocol = new MyProtocolManager();
    peerConnectionListener = new ProtocolManager.ClientConnectionListener(protocol);
    // create channels
    // create server socket
    try {/*from w ww  .  j  av a2s .  c om*/
        serverSocketChannel = ServerSocketChannel.open();
        ServerSocket ss = serverSocketChannel.socket();
        ss.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), port));
        serverPort = ss.getLocalPort();
        logger.info("Open server socket on port " + serverPort);
        serverSocketChannel.configureBlocking(false);
    } catch (IOException e) {
        logger.severe("Error opening ServerSocketChannel: " + e.getMessage());
        failed = true;
        return;
    }
    try {
        selector = new PeerConnectionScheduler(serverSocketChannel);
        selector.setListener(selectorListener);
        selector.start();
    } catch (IOException e) {
        logger.severe("Error starting Selector: " + e.getMessage());
        failed = true;
        return;
    }
    // create and advertise with DnsServer
    dns = new DnsServer();
    NetworkInterface ni = null;
    try {
        ni = NetworkInterface.getByInetAddress(address);//DnsClient.getFirstActiveInterface();
    } catch (Exception e) {
        logger.severe("Could not get NetworkInterface for " + address + ": " + e);
    }
    dns.setNeworkInterface(ni);
    InetAddress ip = getInetAddress(ni);
    logger.info("Binding for multicast to " + ip.getHostAddress());

    id = ip.getHostAddress() + ":" + serverPort;

    String servicename = DnsUtils.getServiceDiscoveryName();
    String name = ip.getHostAddress();
    SrvData srv = new SrvData(1, 1, serverPort, name);
    logger.info("Discoverable " + name + " as " + servicename);
    dns.add(new DnsProtocol.RR(servicename, DnsProtocol.TYPE_SRV, DnsProtocol.CLASS_IN, DEFAULT_TTL,
            DnsProtocol.srvToData(srv)));

    String instancename = "Server on " + ip;
    logger.info("Discoverable as " + instancename + " " + servicename);
    DnsProtocol.RR ptrRR = new DnsProtocol.RR(servicename, DnsProtocol.TYPE_PTR, DnsProtocol.CLASS_IN,
            DEFAULT_TTL, DnsProtocol.ptrToData(instancename, servicename));
    dns.add(ptrRR);

    dns.start();
}

From source file:org.asynchttpclient.async.AbstractBasicTest.java

protected synchronized int findFreePort() throws IOException {
    ServerSocket socket = null;

    try {/*  w  ww.j  a  v  a  2 s  . co m*/
        socket = new ServerSocket(0);

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

From source file:org.apache.flink.runtime.taskmanager.TaskManager.java

/**
 * Searches for an available free port and returns the port number.
 * //from   w  w  w.j  a  v  a 2  s .  c o  m
 * @return An available port.
 * @throws RuntimeException Thrown, if no free port was found.
 */
private static int getAvailablePort() {
    for (int i = 0; i < 50; i++) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            if (port != 0) {
                return port;
            }
        } catch (IOException e) {

            LOG.debug("Unable to allocate port with exception {}", e);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (Throwable t) {
                }
            }
        }
    }

    throw new RuntimeException("Could not find a free permitted port on the machine.");
}

From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java

@Test
public void testSocketSinkNoRetry() throws Exception {
    final ServerSocket server = new ServerSocket(0);
    final int port = server.getLocalPort();

    try {//from  ww w .  j a  v  a 2  s. c om
        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

        Thread serverRunner = new Thread("Test server runner") {

            @Override
            public void run() {
                try {
                    Socket sk = server.accept();
                    sk.close();
                } catch (Throwable t) {
                    error.set(t);
                }
            }
        };
        serverRunner.start();

        SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true);
        simpleSink.open(new Configuration());

        // wait socket server to close
        serverRunner.join();
        if (error.get() != null) {
            Throwable t = error.get();
            t.printStackTrace();
            fail("Error in server thread: " + t.getMessage());
        }

        try {
            // socket should be closed, so this should trigger a re-try
            // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT
            while (true) { // we have to do this more often as the server side closed is not guaranteed to be noticed immediately
                simpleSink.invoke(TEST_MESSAGE + '\n');
            }
        } catch (IOException e) {
            // check whether throw a exception that reconnect failed.
            assertTrue("Wrong exception", e.getMessage().contains(EXCEPTION_MESSGAE));
        } catch (Exception e) {
            fail("wrong exception: " + e.getClass().getName() + " - " + e.getMessage());
        }

        assertEquals(0, simpleSink.getCurrentNumberOfRetries());
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:com.barchart.http.server.TestHttpServer.java

@Before
public void setUp() throws Exception {

    server = new HttpServer();

    basic = new TestRequestHandler("basic", false, 0, 0, false, false);
    async = new TestRequestHandler("async", true, 0, 0, false, false);
    asyncDelayed = new TestRequestHandler("async-delayed", true, 50, 0, false, false);
    clientDisconnect = new TestRequestHandler("", true, 500, 500, false, false);
    error = new TestRequestHandler("error", false, 0, 0, true, false);
    channelError = new TestRequestHandler("channel-error", false, 0, 0, false, true);

    infoHandler = new TestRequestHandler("info", false, 0, 0, false, false);
    serviceHandler = new TestRequestHandler("service", false, 0, 0, false, false);

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();
    s.close();/* w  ww .ja  va2s.  co m*/

    final HttpServerConfig config = new HttpServerConfig().requestHandler("/basic", basic)
            .address(new InetSocketAddress("localhost", port)).parentGroup(new NioEventLoopGroup(1))
            .childGroup(new NioEventLoopGroup(1)).requestHandler("/async", async)
            .requestHandler("/async-delayed", asyncDelayed)
            .requestHandler("/client-disconnect", clientDisconnect)
            .requestHandler("/channel-error", channelError).requestHandler("/error", error)
            .requestHandler("/service/info", infoHandler).requestHandler("/service", serviceHandler)
            .maxConnections(1);

    server.configure(config).listen().sync();

    client = new DefaultHttpClient(new PoolingClientConnectionManager());

}