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, int backlog) throws IOException 

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // Create an unbound server socket
    ServerSocket serverSocket = new ServerSocket();

    // Create a socket address object
    InetSocketAddress endPoint = new InetSocketAddress("localhost", 12900);

    // Set the wait queue size to 100
    int waitQueueSize = 100;

    // Bind the server socket to localhost and at port 12900 with
    // a wait queue size of 100
    serverSocket.bind(endPoint, waitQueueSize);

}

From source file:org.cloudata.core.common.ipc.CServer.java

/**
 * A convience method to bind to a given address and report 
 * better exceptions if the address is not a valid host.
 * @param socket the socket to bind//from   w  ww.j a  v  a 2 s.  com
 * @param address the address to bind to
 * @param backlog the number of connections allowed in the queue
 * @throws BindException if the address can't be bound
 * @throws UnknownHostException if the address isn't a valid host name
 * @throws IOException other random errors from bind
 */
static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        throw new BindException("Problem binding to " + address + "," + e.getMessage());
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        } else {
            throw e;
        }
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.SecureDataNodeStarter.java

@Override
public void init(DaemonContext context) throws Exception {
    System.err.println("Initializing secure datanode resources");
    // We should only start up a secure datanode in a Kerberos-secured cluster
    Configuration conf = new Configuration(); // Skip UGI method to not log in
    if (!conf.get(HADOOP_SECURITY_AUTHENTICATION).equals("kerberos"))
        throw new RuntimeException("Cannot start secure datanode in unsecure cluster");

    // Stash command-line arguments for regular datanode
    args = context.getArguments();/*w  w  w .ja v a 2  s  .  co  m*/

    // Obtain secure port for data streaming to datanode
    InetSocketAddress socAddr = DataNode.getStreamingAddr(conf);
    int socketWriteTimeout = conf.getInt("dfs.datanode.socket.write.timeout", HdfsConstants.WRITE_TIMEOUT);

    ServerSocket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.open().socket() : new ServerSocket();
    ss.bind(socAddr, 0);

    // Check that we got the port we need
    if (ss.getLocalPort() != socAddr.getPort())
        throw new RuntimeException("Unable to bind on specified streaming port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    // Obtain secure listener for web server
    SelectChannelConnector listener = (SelectChannelConnector) HttpServer.createDefaultChannelConnector();
    InetSocketAddress infoSocAddr = DataNode.getInfoAddr(conf);
    listener.setHost(infoSocAddr.getHostName());
    listener.setPort(infoSocAddr.getPort());
    // Open listener here in order to bind to port as root
    listener.open();
    if (listener.getPort() != infoSocAddr.getPort())
        throw new RuntimeException("Unable to bind on specified info port in secure " + "context. Needed "
                + socAddr.getPort() + ", got " + ss.getLocalPort());

    if (ss.getLocalPort() >= 1023 || listener.getPort() >= 1023)
        throw new RuntimeException(
                "Cannot start secure datanode on non-privileged " + " ports. (streaming port = " + ss
                        + " ) (http listener port = " + listener.getConnection() + "). Exiting.");

    System.err.println("Successfully obtained privileged resources (streaming port = " + ss
            + " ) (http listener port = " + listener.getConnection() + ")");

    resources = new SecureResources(ss, listener);
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * A convenience method to bind to a given address and report better exceptions if the address is not a valid host.
 * // w  w w. j  a  v a  2s .co m
 * @param socket
 *          the socket to bind
 * @param address
 *          the address to bind to
 * @param backlog
 *          the number of connections allowed in the queue
 * @throws BindException
 *           if the address can't be bound
 * @throws UnknownHostException
 *           if the address isn't a valid host name
 * @throws IOException
 *           other random errors from bind
 */
public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        BindException bindException = new BindException(
                "Problem binding to " + address + " : " + e.getMessage());
        bindException.initCause(e);
        throw bindException;
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        } else {
            throw e;
        }
    }
}

From source file:org.mule.transport.tcp.TcpServerSocketFactory.java

protected ServerSocket configure(ServerSocket socket, Boolean reuse, InetSocketAddress address, int backlog)
        throws IOException {
    if (null != reuse && reuse.booleanValue() != socket.getReuseAddress()) {
        socket.setReuseAddress(reuse.booleanValue());
    }/*from   w  w w .  j a v a  2  s.c o m*/
    // bind *after* setting so_reuseaddress
    socket.bind(address, backlog);
    return socket;
}

From source file:org.skfiy.typhon.startup.Typhon.java

private void await() {
    ServerSocket serverSocket = null;
    try {//w w  w  .  j  a  va 2 s .c om
        serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(server.getHost(), server.getPort()), 1);
    } catch (IOException e) {
        throw new TyphonException(e);
    }

    for (;;) {
        Socket socket = null;
        try {
            socket = serverSocket.accept();
            InputStream in = socket.getInputStream();
            byte[] cur = server.getShutdown().getBytes(StandardCharsets.UTF_8);
            byte[] buf = new byte[cur.length];
            int l = in.read(buf);
            // 
            if (l == cur.length && Arrays.equals(cur, buf)) {
                break;
            }
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // nothing
                }
            }
        }
    }

    try {
        serverSocket.close();
    } catch (IOException e) {
        // nothing
    }

    // ??
    stop();
}

From source file:org.opennms.netmgt.xmlrpcd.XmlrpcAnticipator.java

public void setupWebServer() throws IOException {
    m_logger.info("XmlrpcAnticipator starting on port number " + m_port);

    m_webServer = new WebServer(m_port) {
        @Override//from   ww w.ja  v a  2 s. c  o  m
        protected ServerSocket createServerSocket(int port, int backlog, InetAddress addr) throws Exception {
            ServerSocket sock = new ServerSocket();
            sock.setReuseAddress(true);
            sock.bind(new InetSocketAddress(addr, port), backlog);
            return sock;
        }

    };
    m_webServer.addHandler("$default", this);
    m_webServer.start();
    waitForStartup();

    m_logger.info("XmlrpcAnticipator running on port number " + m_port);
}

From source file:com.hortonworks.hbase.replication.bridge.HBaseServer.java

/**
 * A convenience method to bind to a given address and report
 * better exceptions if the address is not a valid host.
 * @param socket the socket to bind/*from www .  j  av  a  2s. c o  m*/
 * @param address the address to bind to
 * @param backlog the number of connections allowed in the queue
 * @throws BindException if the address can't be bound
 * @throws UnknownHostException if the address isn't a valid host name
 * @throws IOException other random errors from bind
 */
public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        BindException bindException = new BindException(
                "Problem binding to " + address + " : " + e.getMessage());
        bindException.initCause(e);
        throw bindException;
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        }
        throw e;
    }
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Binds this server to the SocketAddress supplied by DaapConfig
 * //from   w ww  .j a  va 2  s . c  o m
 * @throws IOException
 */
public void bind() throws IOException {

    SocketAddress bindAddr = config.getInetSocketAddress();
    int backlog = config.getBacklog();

    try {

        ssc = ServerSocketChannel.open();
        ServerSocket socket = ssc.socket();

        // BugID: 4546610
        // On Win2k, Mac OS X, XYZ it is possible to bind
        // the same address without rising a SocketException
        // (the Documentation lies)
        socket.setReuseAddress(false);

        try {
            socket.bind(bindAddr, backlog);
        } catch (SocketException err) {
            throw new BindException(err.getMessage());
        }

        ssc.configureBlocking(false);

        if (LOG.isInfoEnabled()) {
            LOG.info("DaapServerNIO bound to " + bindAddr);
        }

        streams = new HashSet();
        connections = new HashSet();
        sessionIds = new HashSet();

    } catch (IOException err) {
        close();
        throw err;
    }
}

From source file:com.github.hrpc.rpc.Server.java

public static void bind(ServerSocket socket, InetSocketAddress address, int backlog, Option conf,
        String rangeConf) throws IOException {
    try {//from   w w  w. ja  va2 s  .c  om
        IntegerRanges range = null;
        if (rangeConf != null) {
            range = conf.getRange(rangeConf, "");
        }
        if (range == null || range.isEmpty() || (address.getPort() != 0)) {
            socket.bind(address, backlog);
        } else {
            for (Integer port : range) {
                if (socket.isBound())
                    break;
                try {
                    InetSocketAddress temp = new InetSocketAddress(address.getAddress(), port);
                    socket.bind(temp, backlog);
                } catch (BindException e) {
                    //Ignored
                }
            }
            if (!socket.isBound()) {
                throw new BindException("Could not find a free port in " + range);
            }
        }
    } catch (SocketException e) {
        throw NetUtils.wrapException(null, 0, address.getHostName(), address.getPort(), e);
    }
}