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.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java

/**
 * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
 * there. Then binds the obtained socket.
 * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
 * IPv6 address. Works on Oracle JDK 1.7.
 *//*w  w w.j  ava  2s  . c  om*/
private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
    while (true) {
        int port = HBaseTestingUtility.randomFreePort();
        InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
        ServerSocketChannel channel = null;
        ServerSocket serverSocket = null;
        try {
            channel = ServerSocketChannel.open();
            serverSocket = channel.socket();
            serverSocket.bind(addr); // This does not work
            break;
        } catch (BindException ex) {
            //continue
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (channel != null) {
                channel.close();
            }
        }
    }
}

From source file:ezbake.thriftrunner.starters.SimpleStarter.java

boolean serverSocketIsFree(int port) {
    ServerSocket socket = null;
    try {//from  www.j a va2 s .co  m
        socket = new ServerSocket();
        socket.setReuseAddress(true);
        socket.bind(new InetSocketAddress(port));
        this.portNumber = socket.getLocalPort();
        return true;
    } catch (final IOException e) {
        return false;
    } finally {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (final IOException e) {
            // should never happen
        }
    }
}

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 {/*  w w  w.  ja  va 2s .c o m*/
        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.openflamingo.remote.thrift.thriftfs.ThriftPluginServer.java

/**
 * Start processing requests./*from  w w w . jav a2s  .c o  m*/
 *
 * @throws IllegalStateException if the server has already been started.
 * @throws java.io.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);
        }

        int socketTimeout = conf.getInt("dfs.thrift.socket.timeout", SOCKET_READ_TIMEOUT);

        TServerTransport transport = new TServerSocket(sock, socketTimeout);
        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, transportFactory, transportFactory,
                new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), options);
    }

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

From source file:org.apache.hadoop.ipc.TestServer.java

@Test
public void testBind() throws Exception {
    Configuration conf = new Configuration();
    ServerSocket socket = new ServerSocket();
    InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0);
    socket.bind(address);
    try {/*from  www. ja v a  2  s  .c om*/
        int min = socket.getLocalPort();
        int max = min + 100;
        conf.set("TestRange", min + "-" + max);

        ServerSocket socket2 = new ServerSocket();
        InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
        Server.bind(socket2, address2, 10, conf, "TestRange");
        try {
            assertTrue(socket2.isBound());
            assertTrue(socket2.getLocalPort() > min);
            assertTrue(socket2.getLocalPort() <= max);
        } finally {
            socket2.close();
        }
    } finally {
        socket.close();
    }
}

From source file:org.apache.hadoop.ipc.TestServer.java

@Test
public void testBindError() throws Exception {
    Configuration conf = new Configuration();
    ServerSocket socket = new ServerSocket();
    InetSocketAddress address = new InetSocketAddress("0.0.0.0", 0);
    socket.bind(address);
    try {/*from   w  ww .  j ava2 s .c  o m*/
        int min = socket.getLocalPort();
        conf.set("TestRange", min + "-" + min);

        ServerSocket socket2 = new ServerSocket();
        InetSocketAddress address2 = new InetSocketAddress("0.0.0.0", 0);
        boolean caught = false;
        try {
            Server.bind(socket2, address2, 10, conf, "TestRange");
        } catch (BindException e) {
            caught = true;
        } finally {
            socket2.close();
        }
        assertTrue("Failed to catch the expected bind exception", caught);
    } finally {
        socket.close();
    }
}

From source file:gridool.util.xfer.TransferServer.java

/**
 * @return binded sock address//from w  w w. j a  v a 2  s  .c  om
 */
public InetSocketAddress setup() throws IOException {
    ServerSocket servSocket = serverChannel.socket();
    servSocket.setReuseAddress(true);
    InetSocketAddress sockaddr = NetUtils.getAnyLocalInetSocketAddress();
    servSocket.bind(sockaddr);
    return sockaddr;
}

From source file:org.reunionemu.jreunion.server.Network.java

public boolean register(InetSocketAddress address) {
    try {// www.j a  v  a2 s .c  om
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(address);
        serverChannel.configureBlocking(false);
        synchronized (this) {
            selector.wakeup();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        }

    } catch (Exception e) {
        if (e instanceof BindException) {
            LoggerFactory.getLogger(Network.class)
                    .error("Port " + address.getPort() + " not available. Is the server already running?", e);
            return false;
        }
    }
    return true;
}

From source file:gridool.util.xfer.TransferServer.java

public void setup(int port) throws IOException {
    ServerSocket servSocket = serverChannel.socket();
    servSocket.setReuseAddress(true);/*from www.  j  av  a 2 s .  c o  m*/
    InetAddress addr = NetUtils.getLocalHost(false);
    InetSocketAddress sockaddr = new InetSocketAddress(addr, port);
    servSocket.bind(sockaddr);
}

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

@Test
public void configureClientSSLSocketCanTimeOut() throws Exception {
    final Semaphore serverCoordination = new Semaphore(0);

    // configure a non-SSL server socket. We will connect
    // a client SSL socket to it and demonstrate that the
    // handshake times out
    final ServerSocket serverSocket = new ServerSocket();
    serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), 0));
    Thread serverThread = new Thread() {
        public void run() {
            serverCoordination.release();
            try (Socket clientSocket = serverSocket.accept()) {
                System.out.println("server thread accepted a connection");
                serverCoordination.acquire();
            } catch (Exception e) {
                System.err.println("accept failed");
                e.printStackTrace();//from   ww w  . jav a 2  s.co m
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                // ignored
            }
            System.out.println("server thread is exiting");
        }
    };
    serverThread.setName("SocketCreatorJUnitTest serverSocket thread");
    serverThread.setDaemon(true);
    serverThread.start();

    serverCoordination.acquire();

    SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.SERVER);

    int serverSocketPort = serverSocket.getLocalPort();
    try {
        Awaitility.await("connect to server socket").atMost(30, TimeUnit.SECONDS).until(() -> {
            try {
                Socket clientSocket = socketCreator.connectForClient(
                        SocketCreator.getLocalHost().getHostAddress(), serverSocketPort, 2000);
                clientSocket.close();
                System.err.println(
                        "client successfully connected to server but should not have been able to do so");
                return false;
            } catch (SocketTimeoutException e) {
                // we need to verify that this timed out in the handshake
                // code
                System.out.println("client connect attempt timed out - checking stack trace");
                StackTraceElement[] trace = e.getStackTrace();
                for (StackTraceElement element : trace) {
                    if (element.getMethodName().equals("configureClientSSLSocket")) {
                        System.out.println("client connect attempt timed out in the appropriate method");
                        return true;
                    }
                }
                // it wasn't in the configuration method so we need to try again
            } catch (IOException e) {
                // server socket may not be in accept() yet, causing a connection-refused
                // exception
            }
            return false;
        });
    } finally {
        serverCoordination.release();
    }
}