Example usage for java.net ServerSocket bind

List of usage examples for java.net ServerSocket bind

Introduction

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

Prototype

public void bind(SocketAddress endpoint) throws IOException 

Source Link

Document

Binds the ServerSocket to a specific address (IP address and port number).

Usage

From source file:com.redblackit.web.server.HostNetUtils.java

/**
 * Check if port is available/*w ww.ja va  2 s  .  com*/
 * 
 * @param port
 * @return
 */
private static boolean isPortAvailable(int port) {
    ServerSocket serverSocket;
    try {
        serverSocket = new ServerSocket();
    } catch (IOException ex) {
        throw new IllegalStateException("Unable to create ServerSocket.", ex);
    }

    try {
        InetSocketAddress sa = new InetSocketAddress(port);
        serverSocket.bind(sa);
        return true;
    } catch (IOException ex) {
        return false;
    } finally {
        try {
            serverSocket.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:org.apache.hadoop.gateway.GatewayServer.java

private static void checkAddressAvailability(InetSocketAddress address) throws IOException {
    ServerSocket socket = new ServerSocket();
    socket.bind(address);
    socket.close();/*from   www.j ava 2s .  com*/
}

From source file:helma.main.Server.java

/**
 *  Check whether a server port is available by trying to open a server socket
 *///from  w  w w  .  j  a va2 s.co m
private static void checkPort(InetSocketAddress endpoint) throws IOException {
    try {
        ServerSocket sock = new ServerSocket();
        sock.bind(endpoint);
        sock.close();
    } catch (IOException x) {
        throw new IOException("Error binding to " + endpoint + ": " + x.getMessage());
    }
}

From source file:org.apache.helix.TestHelper.java

public static int getRandomPort() throws IOException {
    ServerSocket sock = new ServerSocket();
    sock.bind(null);
    int port = sock.getLocalPort();
    sock.close();// ww w . j  a  va  2  s. c o  m
    return port;
}

From source file:gov.hhs.fha.nhinc.lift.ClientApp.java

private void startClient() {

    try {//  w w  w.j  a va 2  s.c o m
        String clientIP = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_CLIENT_IP);
        String clientPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_CLIENT_PORT);
        SocketAddress saddr = new InetSocketAddress(clientIP, Integer.parseInt(clientPort));
        ServerSocket server = new ServerSocket();
        server.bind(saddr);
        log.debug("Client listening on " + saddr);

        ClientPropertiesFacade props = new ClientPropertiesService();
        ConsumerProxyPropertiesFacade proxyProps = new ConsumerProxyPropertiesFacadeRI();
        proxyProps.setTrustStore();
        proxyProps.setKeyStoreProperty();

        LSTClientManager manager = new LSTClientManager(props, proxyProps);
        SocketClientManagerController con = new SocketClientManagerController(server, manager);

        (new Thread(con)).start();
        System.out.println("ClientApp started. ");

    } catch (PropertyAccessException ex) {
        log.error(ex.getMessage());
    } catch (IOException ex) {
        log.error(ex.getMessage());
    }
}

From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnectorManager.java

/**
 * This method will create a tunnel of a type defined by the properties
 * facade and will then bind a local temporary port for a client app to use
 * to communicate through the proxy tunnel.  Returns an address to the
 * local server a client can talk to.//ww w.  j  a v a2  s. c  o m
 *
 * @param token
 * @param serverProxyAddress
 * @param serverProxyPort
 * @return
 * @throws IOException
 */
public InetSocketAddress startConnector(RequestToken token, InetAddress serverProxyAddress, int serverProxyPort,
        int bufferSize, ConsumerProxyPropertiesFacade props, SocketClientManagerController controller)
        throws IOException {
    /*
     * Attempts to start up a connection with the desired server proxy.
     */

    // Note that both client and server are closed when the thread completes
    log.debug("Creating Client instance to connect to server proxy: " + serverProxyAddress + ":"
            + serverProxyPort);
    Client client = props.getClientInstance(serverProxyAddress, serverProxyPort, token);

    /*
     * Start up a socket server bound to the local proxy hostname and to a
     * port unique to this request.
     */
    InetAddress localProxyAddress = props.getClientProxyAddress();
    log.debug("Local client proxy address set as: " + localProxyAddress);

    InetSocketAddress connectorAddress = new InetSocketAddress(localProxyAddress, 0);
    log.debug("Starting server socket for client to access on port: " + connectorAddress.getPort());

    // Note that both client and server are closed when the thread completes
    ServerSocket server = new ServerSocket();
    server.bind(connectorAddress);
    log.debug("Creating Server bound: " + server.getInetAddress() + ": " + server.getLocalPort());

    ClientConnector connector = new ClientConnector(server, client, bufferSize, controller);
    Thread conn = new Thread(connector);

    log.debug("Starting new Client Connector thread.");
    conn.start();

    return new InetSocketAddress(server.getInetAddress(), server.getLocalPort());
}

From source file:org.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java

/**
 * Creates and binds a regular ServerSocket.
 *//* w  ww  .ja  v  a  2 s . c o m*/
private void bindServerSocket(InetAddress inetAddr) throws IOException {
    while (true) {
        int port = HBaseTestingUtility.randomFreePort();
        InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.bind(addr);
            break;
        } catch (BindException ex) {
            //continue
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
        }
    }
}

From source file:com.kixeye.kixmpp.client.KixmppClientTest.java

@Before
public void setUp() throws Exception {
    domain = UUID.randomUUID().toString().replace("-", "");
    username = UUID.randomUUID().toString().replace("-", "");
    password = UUID.randomUUID().toString().replace("-", "");
    resource = UUID.randomUUID().toString().replace("-", "");

    ServerSocket socketServer = new ServerSocket();
    socketServer.bind(null);

    port = socketServer.getLocalPort();/* w w  w . j  a  v  a  2s  .  co  m*/
    socketServer.close();

    StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry();

    final Entity adminJID = EntityImpl.parseUnchecked(username + "@" + domain);
    final AccountManagement accountManagement = (AccountManagement) providerRegistry
            .retrieve(AccountManagement.class);

    if (!accountManagement.verifyAccountExists(adminJID)) {
        accountManagement.addUser(adminJID, password);
    }

    TCPEndpoint tcpEndpoint = new TCPEndpoint();
    tcpEndpoint.setPort(port);

    try (InputStream certStream = this.getClass().getResourceAsStream("/bogus_mina_tls.cert")) {
        server = new XMPPServer(domain);
        server.addEndpoint(tcpEndpoint);
        server.setStorageProviderRegistry(providerRegistry);
        server.setTLSCertificateInfo(certStream, "boguspw");

        server.start();

        server.addModule(new SoftwareVersionModule());
        server.addModule(new EntityTimeModule());
        server.addModule(new XmppPingModule());
        server.addModule(new InBandRegistrationModule());
        server.addModule(new AdhocCommandsModule());
        final ServiceAdministrationModule serviceAdministrationModule = new ServiceAdministrationModule();
        // unless admin user account with a secure password is added, this will be not become effective
        serviceAdministrationModule.setAddAdminJIDs(Arrays.asList(adminJID));
        server.addModule(serviceAdministrationModule);
    }
}

From source file:com.l2jfree.network.mmocore.AcceptorThread.java

public void openServerSocket(InetAddress address, int port) throws IOException {
    ServerSocketChannel selectable = ServerSocketChannel.open();
    selectable.configureBlocking(false);

    ServerSocket ss = selectable.socket();
    ss.setReuseAddress(true);// w ww  . j  a v a  2 s  . c  om
    ss.setReceiveBufferSize(getBufferSize());
    if (address == null) {
        ss.bind(new InetSocketAddress(port));
    } else {
        ss.bind(new InetSocketAddress(address, port));
    }
    selectable.register(getSelector(), SelectionKey.OP_ACCEPT);
}

From source file:org.apache.hadoop.thriftfs.ThriftPluginServer.java

/**
 * Start processing requests.//from   w  w  w . j  a v  a 2  s  . co m
 * 
 * @throws IllegalStateException if the server has already been started.
 * @throws IOException on network errors.
 */
public void start() throws IOException {
    String hostname = address.getAddress().getHostAddress();

    synchronized (this) {
        if (server != null) {
            throw new IllegalStateException("Thrift server already started");
        }
        LOG.info("Starting Thrift server");
        ServerSocket sock = new ServerSocket();
        sock.setReuseAddress(true);
        if (port == 0) {
            sock.bind(null);
            address = new InetSocketAddress(hostname, sock.getLocalPort());
            port = address.getPort();
        } else {
            sock.bind(address);
        }
        TServerTransport transport = new TServerSocket(sock, SOCKET_READ_TIMEOUT);
        SanerThreadPoolServer.Options options = new SanerThreadPoolServer.Options();
        options.minWorkerThreads = conf.getInt("dfs.thrift.threads.min", 5);
        options.maxWorkerThreads = conf.getInt("dfs.thrift.threads.max", 20);
        options.stopTimeoutVal = conf.getInt("dfs.thrift.timeout", 60);
        options.stopTimeoutUnit = TimeUnit.SECONDS;
        options.queueSize = conf.getInt("dfs.thrift.queue.size", 4 * options.maxWorkerThreads);

        server = new SanerThreadPoolServer(processorFactory, transport, new TTransportFactory(),
                new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), options);
    }

    Thread t = new Thread(this);
    t.start();
    LOG.info("Thrift server listening on " + hostname + ":" + port);
}