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:org.gcaldaemon.core.ldap.LDAPListener.java

LDAPListener(ContactLoader loader, FilterMask[] hosts, FilterMask[] addresses, int port) throws Exception {

    // Starting server
    log.info("LDAP server starting on port " + port + "...");

    // Store pointers
    this.loader = loader;
    this.hosts = hosts;
    this.addresses = addresses;

    // Allocate an unbound server socket channel
    serverChannel = ServerSocketChannel.open();

    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();

    // Set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(port));

    // Set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);

    // Create a new Selector for use below
    selector = Selector.open();/* ww w  . j  a v  a 2s . c  o m*/

    // Register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);

    // Start thread
    start();
}

From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java

@Test
public void specificPortsViaPropertiesWithClash() throws Exception {
    int managementPort = ports.get().management;
    ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(managementPort));
    try {/*w w  w  .j a  v  a 2s.c  om*/
        EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:" + ports.get().server,
                "management.port:" + ports.get().management);
        this.applicationContext.register(RootConfig.class, EndpointConfig.class, BaseConfiguration.class,
                EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class);
        this.thrown.expect(WebServerException.class);
        this.applicationContext.refresh();
    } finally {
        serverSocket.close();
    }
}

From source file:org.cloudata.core.commitlog.CommitLogServer.java

private int startFileTransferChannel(String dirName, FileChannel[] fileChannelList) {
    int port = -1;
    try {//from w  w  w .ja  va  2  s  . co  m
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ServerSocket serverSocket = ssc.socket();
        serverSocket.bind(null);
        port = serverSocket.getLocalPort();

        new FileTransferThread(dirName, ssc, fileChannelList).start();
        //LOG.info("File transfer thread is started and read method is done");
    } catch (IOException e) {
        LOG.warn("starting file transfer is fail", e);
    }

    return port;
}

From source file:runtime.starter.MPJYarnClient.java

private int findPort(ServerSocket sock) {
    int minPort = 25000;
    int maxPort = 40000;
    int selectedPort;

    /* The loop generates a random port number, opens a socket on 
     * the generated port//from  w w  w.j a  v a 2  s .co m
     */

    while (true) {
        Random rand = new Random();
        selectedPort = (rand.nextInt((maxPort - minPort) + 1) + minPort);

        try {
            sock.bind(new InetSocketAddress(selectedPort));
        } catch (IOException e) {
            System.err.println("[MPJYarnClient.java]:- " + selectedPort
                    + "]Port already in use. Checking for a new port..");
            continue;
        }
        break;
    }

    return selectedPort;
}

From source file:org.freedesktop.dbus.Transport.java

@SuppressWarnings("resource")
public void connect(BusAddress address, int timeout) throws IOException {
    log.info("Connecting to " + address);
    OutputStream out = null;// ww  w  . j  a v a2s  .  c om
    InputStream in = null;
    AFUNIXSocket us = null;
    Socket s = null;
    int mode = 0;
    int types = 0;
    if ("unix".equals(address.getType())) {
        types = SASL.AUTH_EXTERNAL;
        File sockFile = null;
        boolean abstractSock = false;
        if (null != address.getParameter("abstract")) {
            sockFile = new File(address.getParameter("abstract"));
            abstractSock = true;
        } else if (null != address.getParameter("path")) {
            sockFile = new File(address.getParameter("path"));
        }

        if (null != address.getParameter("listen")) {
            mode = SASL.MODE_SERVER;
            AFUNIXServerSocket uss = AFUNIXServerSocket.newInstance();
            uss.bind(new AFUNIXSocketAddress(sockFile, abstractSock));
            uss.setPassCred(true);
            s = uss.accept();
        } else {
            mode = SASL.MODE_CLIENT;
            us = AFUNIXSocket.newInstance();

            us.connect(new AFUNIXSocketAddress(sockFile, abstractSock));
            us.setPassCred(true);
            s = us;
        }

    } else if ("tcp".equals(address.getType())) {
        types = SASL.AUTH_SHA;
        if (null != address.getParameter("listen")) {
            mode = SASL.MODE_SERVER;
            ServerSocket ss = new ServerSocket();
            ss.bind(new InetSocketAddress(address.getParameter("host"),
                    Integer.parseInt(address.getParameter("port"))));
            s = ss.accept();
        } else {
            mode = SASL.MODE_CLIENT;
            s = new Socket();
            s.connect(new InetSocketAddress(address.getParameter("host"),
                    Integer.parseInt(address.getParameter("port"))));
        }
    } else {
        throw new IOException("unknown address type " + address.getType());
    }

    in = s.getInputStream();
    out = s.getOutputStream();

    if (!(new SASL()).auth(mode, types, address.getParameter("guid"), out, in, us)) {
        out.close();
        in.close();
        s.close();
        throw new IOException("Failed to auth");
    }

    if (log.isTraceEnabled()) {
        log.trace("Setting timeout to " + timeout + " on Socket");
    }
    s.setSoTimeout(timeout);

    this.mout = new MessageWriter(out);
    this.min = new MessageReader(in);

    log.info("Connection open");
}

From source file:org.rhq.storage.installer.StorageInstaller.java

private void isPortBound(String address, int port, String portName, int potentialErrorCode)
        throws StorageInstallerException {
    ServerSocket serverSocket = null;
    try {//from ww  w . j a  va  2  s .c  o  m
        serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(address, port));
    } catch (BindException e) {
        throw new StorageInstallerException("The " + portName + " (" + address + ":" + port
                + ") is already in use. " + "Installation cannot proceed.", potentialErrorCode);
    } catch (IOException e) {
        // We only log a warning here and let the installation proceed in case the
        // exception is something that can be ignored.
        log.warn("An unexpected error occurred while checking the " + portName + " port", e);
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                log.error("An error occurred trying to close the connection to the " + portName, e);
            }
        }
    }
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

private void _init(TaskRunConfig runConfig) throws Exception {
    config = runConfig;/*from w ww. j  a  v a 2  s .  c o  m*/
    mapstats = new TreeMapperStats(log);

    resolve();

    if (nodeCache != null)
        TreeCommonParameters.setDefaultCleanQueueSize(nodeCache);
    if (trashInterval != null)
        TreeCommonParameters.setDefaultTrashInterval(trashInterval);
    if (trashTimeLimit != null)
        TreeCommonParameters.setDefaultTrashTimeLimit(trashTimeLimit);
    if (storage != null) {
        if (storage.maxCacheSize != null)
            TreeCommonParameters.setDefaultMaxCacheSize(storage.maxCacheSize);
        if (storage.maxCacheMem != null)
            TreeCommonParameters.setDefaultMaxCacheMem(storage.maxCacheMem);
        if (storage.maxPageSize != null)
            TreeCommonParameters.setDefaultMaxPageSize(storage.maxCacheSize);
        if (storage.maxPageMem != null)
            TreeCommonParameters.setDefaultMaxPageMem(storage.maxPageMem);
        if (storage.memSample != null)
            TreeCommonParameters.setDefaultMemSample(storage.memSample);
    }

    if (Strings.isEmpty(localhost)) {
        localhost = InetAddress.getLocalHost().getHostAddress();
    }
    log.info("[init] java=" + System.getProperty("java.vm.version") + " query=" + enableQuery + " http="
            + enableHttp + " jmx=" + enableJmx + " live=" + live);
    log.info("[init] host=" + localhost + " port=" + port + " target=" + root + " job=" + config.jobId);

    Path treePath = Paths.get(runConfig.dir, "data");
    tree = new ConcurrentTree(Files.initDirectory(treePath.toFile()));
    bench = new Bench(EnumSet.allOf(BENCH.class), 1000);

    if (enableHttp) {
        jetty = new Server(port > 0 ? port++ : 0);
        jetty.start();
        int httpPort = jetty.getConnectors()[0].getLocalPort();
        log.info("[init.http] http://" + localhost + ":" + httpPort + "/");
        Files.write(new File("job.port"), Bytes.toBytes(Integer.toString(httpPort)), false);
    }

    if (enableJmx) {
        int queryPort = 0;
        jmxname = new ObjectName("com.addthis.hydra:type=Hydra,node=" + queryPort);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mapstats, jmxname);
        ServerSocket ss = new ServerSocket();
        ss.setReuseAddress(true);
        ss.bind(port > 0 ? new InetSocketAddress(port++) : null);
        int jmxport = ss.getLocalPort();
        ss.close();
        if (jmxport == -1) {
            log.warn("[init.jmx] failed to get a port");
        } else {
            try {
                jmxremote = new MBeanRemotingSupport(jmxport);
                jmxremote.start();
                log.info("[init.jmx] port=" + jmxport);
            } catch (Exception e) {
                log.warn("[init.jmx] err=" + e);
            }
        }
    }

    if (config.jobId != null && live && livePort > -1) {
        QueryEngine liveQueryEngine = new QueryEngine(tree);
        connectToMesh(treePath.toFile(), runConfig.jobId, liveQueryEngine);
    }

    startTime = System.currentTimeMillis();

    if (pre != null) {
        log.warn("pre-chain: " + pre);
        processBundle(new KVBundle(), pre);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.AvatarNode.java

/**
 * Tries to bind to the address specified in ZooKeeper, this will always fail
 * if the primary is alive either on the same machine or on a remote machine.
 *///from ww  w  . jav a 2  s. c o m
private static void isPrimaryAlive(String zkRegistry) throws IOException {
    String parts[] = zkRegistry.split(":");
    if (parts.length != 2) {
        throw new IllegalArgumentException("Invalid Address : " + zkRegistry);
    }
    String host = parts[0];
    int port = Integer.parseInt(parts[1]);
    InetSocketAddress clientSocket = new InetSocketAddress(host, port);
    ServerSocket socket = new ServerSocket();
    socket.bind(clientSocket);
    socket.close();
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

protected final void doWithBlockedPort(BlockedPortAction action) throws IOException {
    int port = SocketUtils.findAvailableTcpPort(40000);
    ServerSocket serverSocket = new ServerSocket();
    for (int i = 0; i < 10; i++) {
        try {/*w w w .  j  av  a  2  s  .  c o m*/
            serverSocket.bind(new InetSocketAddress(port));
            break;
        } catch (Exception ex) {
        }
    }
    try {
        action.run(port);
    } finally {
        serverSocket.close();
    }
}

From source file:uk.ac.horizon.ubihelper.service.PeerManager.java

public PeerManager(Service service) {
    this.service = service;
    // Note: meant to open database on another thread?!
    database = new PeersOpenHelper(service).getWritableDatabase();

    protocol = new MyProtocolManager();
    peerConnectionListener = new OnPeerConnectionListener(protocol);
    remoteChannelTimer = new Timer();

    wifi = (WifiManager) service.getSystemService(Service.WIFI_SERVICE);

    try {//from  www.j  a v  a 2 s  .  c om
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
        Log.e(TAG, "Could not get MessageDigest: " + e);
    }
    try {
        serverSocketChannel = ServerSocketChannel.open();
        ServerSocket ss = serverSocketChannel.socket();
        ss.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
        serverPort = ss.getLocalPort();
        serverSocketChannel.configureBlocking(false);
    } catch (IOException e) {
        Log.w(TAG, "Error opening ServerSocketChannel: " + e.getMessage());
    }
    try {
        selector = new PeerConnectionScheduler(serverSocketChannel);
        selector.setListener(selectorListener);
        selector.start();
    } catch (IOException e) {
        Log.w(TAG, "Error starting Selector: " + e.getMessage());
    }
}