Example usage for java.nio.channels ServerSocketChannel accept

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

Introduction

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

Prototype

public abstract SocketChannel accept() throws IOException;

Source Link

Document

Accepts a connection made to this channel's socket.

Usage

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void canAcceptSocketConnections() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/*from   www  .  j a v a2s. c om*/
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void afterReadyInterestIsCleared() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);//from ww w.  jav  a  2s. c  om
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void noReadyCallbackIfInterestRemoved() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);//from   www.ja  va 2s .c om
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });

    // Wait for registration, in other case we get unpredictable timing related results due to late registration
    while (key.get() == null) {
        Thread.sleep(10);
    }

    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    hub.hub().removeInterestAccept(key.get());
    // wait for the interest accept to be removed
    while ((key.get().interestOps() & SelectionKey.OP_ACCEPT) != 0) {
        Thread.sleep(10);
    }
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

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

private void createNewClientConnection(SelectionKey key) {
    SocketChannel socket = null;// w  w  w  . jav a 2s .  c  o m
    try {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        socket = serverSocketChannel.accept();
    } catch (IOException e) {
        LOGGER.error("Cannot accept the connection from a new client", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    SelectionKey newKey;
    try {
        socket.configureBlocking(false);
        newKey = socket.register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
        LOGGER.error("Cannot add a new client socket to the selector", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    ServerConnection connection = newConnection(newKey);
    newKey.attach(connection);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("[" + threadName + "] New connection from " + connection);
    }
}

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

/**
 * Starts server in non-blocking mode./*from  w  w w  .j  a  va  2  s  .  com*/
 * @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:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {//from  w  ww .  ja  va 2 s  .com
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}