Example usage for java.nio.channels ServerSocketChannel socket

List of usage examples for java.nio.channels ServerSocketChannel socket

Introduction

In this page you can find the example usage for java.nio.channels ServerSocketChannel socket.

Prototype

public abstract ServerSocket socket();

Source Link

Document

Retrieves a server socket associated with this channel.

Usage

From source file:org.commoncrawl.io.internal.NIOServerTCPSocket.java

private static void setListenerSocketOptions(ServerSocketChannel channel) throws IOException {
    channel.socket().setReuseAddress(true);
    channel.configureBlocking(false);//from  w  ww .j  a va  2s . c om
}

From source file:org.jnode.net.NServerSocket.java

private CompletableFuture<ServerSocketChannel> createServerChannel(int port) {
    CompletableFuture cf = new CompletableFuture<>();
    try {/*from www .  j  av a2 s .co m*/
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port));
        cf.complete(ssc);
    } catch (Exception e) {
        cf.completeExceptionally(e);
    }
    return cf;
}

From source file:org.pvalsecc.comm.MultiplexedServer.java

/**
 * Attempt to create the listening socket for at most 5 minutes.
 *///from  w  w w. j  a v a  2 s.c o  m
private void createSocket() {
    while (!stop) {
        ServerSocketChannel serverSocketChannel = null;

        try {
            synchronized (selectorLOCK) {
                if (!stop) {
                    selector = Selector.open();
                }
            }

            if (!stop) {
                serverSocketChannel = ServerSocketChannel.open();
                //serverSocketChannel.socket().setReuseAddress(true);
                serverSocketChannel.configureBlocking(false);
                serverSocketChannel.socket().bind(address);
                serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                LOGGER.info("[" + threadName + "] Start to listen on " + address);
            }

            break;
        } catch (IOException e) {
            //noinspection StringContatenationInLoop
            LOGGER.warn("Cannot start to listen on " + threadName + " (will try again later)", e);

            SystemUtilities.safeClose(serverSocketChannel);

            try {
                Thread.sleep(5000);
            } catch (InterruptedException ignored) {
                //ignored
            }
        }
    }
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in non-blocking mode./*from   w w w.  jav  a2 s.  c  o m*/
 * @since 1.4.5
 */
private void runNonBlocking(TheClient theClient) throws Exception {
    int selectCount = 0;
    Iterator iterator = null;
    SelectionKey key = null;
    ServerSocketChannel serverChannel = null;
    SocketChannel socketChannel = null;
    Socket client = null;
    ClientHandler _chPolled = null;
    boolean stopServerProcessed = false;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();
    registerChannelRequestMap = new HashMap();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    while (true) {
        selectCount = selector.select(500);
        //selectCount = selector.select();//for testing

        //check for any pending registerChannel req.
        synchronized (registerChannelRequestMap) {
            if (registerChannelRequestMap.size() > 0) {
                RegisterChannelRequest req = null;
                Object hashkey = null;
                iterator = registerChannelRequestMap.keySet().iterator();
                while (iterator.hasNext()) {
                    hashkey = iterator.next();
                    req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey);
                    req.register(getSelector());
                }
                iterator = null;
                registerChannelRequestMap.clear();
            } //if
        } //sync

        if (stopServer == true && stopServerProcessed == false) {
            logger.warning("Closing " + getName());
            serverSocketChannel.close();
            stopServerProcessed = true;

            server = null;
            serverSocketChannel = null;

            setServiceState(Service.STOPPED);
            logger.warning("Closed " + getName());

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

        if (stopServer == false && stopServerProcessed == true) {
            logger.finest("Server must have re-started.. will break");
            break;
        }

        if (selectCount == 0 && stopServerProcessed == true) {
            java.util.Set keyset = selector.keys();
            if (keyset.isEmpty() == true && getClientCount() <= 0) {
                break;
            } else {
                continue;
            }
        } else if (selectCount == 0) {
            continue;
        }

        iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            key = (SelectionKey) iterator.next();

            if (key.isValid() == false) {
                iterator.remove();
                continue;
            }

            if (key.isAcceptable() && stopServer == false) {
                logger.finest("Key is Acceptable");
                serverChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverChannel.accept();

                if (socketChannel == null) {
                    iterator.remove();
                    continue;
                }

                client = socketChannel.socket();

                if (linger < 0) {
                    client.setSoLinger(false, 0);
                } else {
                    client.setSoLinger(true, linger);
                }

                client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

                if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
                    client.setTrafficClass(socketTrafficClass);//low delay=10
                }

                //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

                if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
                    client.setSendBufferSize(
                            getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
                    //logger.fine("SendBufferSize: "+client.getSendBufferSize());
                }

                if (checkAccessConstraint(client) == false) {
                    iterator.remove();
                    continue;
                }

                socketChannel.configureBlocking(false);
                theClient.setTrusted(getSkipValidation());
                theClient.setSocket(socketChannel.socket());
                theClient.setSocketChannel(socketChannel);

                if (clientDataClass != null) {
                    if (getClientDataPool() == null) {
                        clientData = (ClientData) clientDataClass.newInstance();
                    } else {
                        //borrow a object from pool
                        clientData = (ClientData) getClientDataPool().borrowObject();
                    }
                    theClient.setClientData(clientData);
                }

                //Check if max connection has reached
                if (getSkipValidation() != true && maxConnection != -1
                        && getClientHandlerPool().getNumActive() >= maxConnection) {
                    theClient.setClientEvent(ClientEvent.MAX_CON);
                } else {
                    theClient.setClientEvent(ClientEvent.ACCEPT);
                }

                try {
                    _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
                    logger.finest("Asking " + _chPolled.getName() + " to handle.");
                    _chPolled.handleClient(theClient);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee);
                    logger.warning("Closing SocketChannel [" + serverChannel.socket()
                            + "] since no ClientHandler available.");
                    socketChannel.close();
                }

                if (_chPolled != null) {
                    try {
                        getClientPool().addClient(_chPolled, true);
                    } catch (java.util.NoSuchElementException nsee) {
                        logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                        //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available.");
                        //socketChannel.close();
                        //returnClientHandlerToPool(_chPolled);
                    }
                    _chPolled = null;
                }
                socketChannel = null;
                client = null;

                setSkipValidation(false);//reset it back
            } else if (key.isValid() && key.isReadable()) {
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName());
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    _ch.addEvent(ClientEvent.READ);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.READ);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (key.isValid() && key.isWritable()) {
                if (getClientPool().shouldNioWriteHappen() == false) {
                    continue; //no need to remove the key
                }
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName());
                    //remove OP_WRITE from interest set
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    _ch.addEvent(ClientEvent.WRITE);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.WRITE);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (stopServer == true && key.isAcceptable()) {
                //we will not accept this key
                setSkipValidation(false);//reset it back
            } else {
                logger.warning("Unknown key got in SelectionKey: " + key);
            }
            iterator.remove(); //Remove key

            Thread.yield();
        } //end of iterator
        iterator = null;
    } //end of loop
}

From source file:org.springframework.boot.devtools.tunnel.client.TunnelClient.java

/**
 * Start the client and accept incoming connections on the port.
 * @throws IOException in case of I/O errors
 */// w w w . jav  a 2s .co  m
public synchronized void start() throws IOException {
    Assert.state(this.serverThread == null, "Server already started");
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
    logger.trace("Listening for TCP traffic to tunnel on port " + this.listenPort);
    this.serverThread = new ServerThread(serverSocketChannel);
    this.serverThread.start();
}

From source file:org.wso2.carbon.appmgt.impl.idp.sso.SSOConfiguratorUtil.java

/**
 * Utility method used to check availability of service on host/port.
 * @param host/*from   w w  w  .jav a  2  s  . c o m*/
 * @param port
 * @return true/false can connect
 */
public static boolean isUp(String host, int port) {
    try {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(true);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        socketChannel.socket().bind(inetSocketAddress);
        socketChannel.socket().close();
        return false;
    } catch (IOException e) {
        return true;
    }
}

From source file:xbird.server.services.RemotePagingService.java

private void acceptConnections(final ServerSocketChannel channel) throws IOException {
    // set to non blocking mode
    channel.configureBlocking(false);/*from   ww w.  j a  v a  2s . c  o m*/

    // Bind the server socket to the local host and port
    InetAddress host = InetAddress.getLocalHost();
    InetSocketAddress sockAddr = new InetSocketAddress(host, PORT);
    ServerSocket socket = channel.socket();
    //socket.setReuseAddress(true);
    socket.bind(sockAddr);

    // Register accepts on the server socket with the selector. This
    // step tells the selector that the socket wants to be put on the
    // ready list when accept operations occur.
    Selector selector = Selector.open();

    ByteBuffer cmdBuffer = ByteBuffer.allocateDirect(MAX_COMMAND_BUFLEN);
    IOHandler ioHandler = new IOHandler(cmdBuffer);
    AcceptHandler acceptHandler = new AcceptHandler(ioHandler);

    channel.register(selector, SelectionKey.OP_ACCEPT, acceptHandler);

    int n;
    while ((n = selector.select()) > 0) {
        // Someone is ready for I/O, get the ready keys
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> keyItor = selectedKeys.iterator();
        while (keyItor.hasNext()) {
            SelectionKey key = keyItor.next();
            keyItor.remove();
            // The key indexes into the selector so you
            // can retrieve the socket that's ready for I/O
            Handler handler = (Handler) key.attachment();
            try {
                handler.handle(key);
            } catch (CancelledKeyException cke) {
                ;
            } catch (IOException ioe) {
                LOG.fatal(ioe);
                NIOUtils.cancelKey(key);
            } catch (Throwable e) {
                LOG.fatal(e);
                NIOUtils.cancelKey(key);
            }
        }
    }
}