Example usage for java.nio.channels SocketChannel configureBlocking

List of usage examples for java.nio.channels SocketChannel configureBlocking

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel configureBlocking.

Prototype

public final SelectableChannel configureBlocking(boolean block) throws IOException 

Source Link

Document

Adjusts this channel's blocking mode.

Usage

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

SocketInfo select() throws IOException {
    log.trace("select()");

    Selector selector = Selector.open();

    SocketInfo selectedSocket = initConnections(selector);
    if (selectedSocket != null) {
        return selectedSocket;
    }// w  w w.  jav a 2s .co m

    URI selectedAddress = null;
    SocketChannel channel = null;
    try {
        SelectionKey key = selectFirstConnectedSocketChannel(selector);
        if (key == null) {
            return null;
        }

        channel = (SocketChannel) key.channel();
        selectedAddress = (URI) key.attachment();
    } finally {
        try {
            closeSelector(selector, channel);
        } catch (Exception e) {
            log.error("Error while closing selector", e);
        }
    }

    if (channel != null) {
        channel.configureBlocking(true);
        return new SocketInfo(selectedAddress, channel.socket());
    }

    return null;
}

From source file:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java

public ConnectionConfiguration getSafeXmppConnectionConfiguration(final String xmppServiceName,
        final String email, final boolean hasFailed) throws XMPPConfigurationException {

    debuglog("Creating new XMPP connection");

    if (!mConnectivityManager.isConnected()) {
        debuglog("No network.");
        throw new XMPPConfigurationException("No network.");
    }// w ww  .  j  a va 2 s  .  c  o m

    final ConnectionConfiguration xmppConfig;
    if (hasFailed) {
        debuglog("Getting config from cloud because previous connection attempt failed.");
        xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
    } else {
        debuglog("Getting config from config provider.");
        ConnectionConfiguration tmpXmppConfig = getBasicXMPPConfigurationFromConfigProvider(xmppServiceName);
        if (tmpXmppConfig == null) {
            debuglog("Getting config from cloud because config provider is empty.");
            xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
        } else
            xmppConfig = tmpXmppConfig;
    }

    if (xmppConfig == null) {
        debuglog("No xmpp configuration found.");
        throw new XMPPConfigurationException("No xmpp configuration found.");
    }

    final HostAddress[] hostAddresses = xmppConfig.getHosts();
    if (hostAddresses.length == 0) {
        debuglog("Error: did not receive any XMPP DNS SRV record");
        throw new XMPPConfigurationException("Did not find any XMPP DNS SRV record");
    } else if (hostAddresses.length == 1 && xmppServiceName.equals(hostAddresses[0].getHost())
            && XMPP_DEFAULT_PORT == hostAddresses[0].getPort()) {
        buglog("Using fallback value for DNS SRV (but network is up): " + hostAddresses[0]);
    }

    debuglog("Found XMPP DNS SRV records:");
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        debuglog("- host = " + hostAddresses[i]);
    }

    final int preferredXMPPPort = hostAddresses[hostAddresses.length - 1].getPort();
    debuglog("Preferred XMPP port is " + preferredXMPPPort);

    // Do non-blocking TCP connect attempts
    Map<HostAddress, SocketChannel> allChannels = new HashMap<HostAddress, SocketChannel>();
    Map<HostAddress, SocketChannel> remainingChannels = new HashMap<HostAddress, SocketChannel>();
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        final HostAddress ha = hostAddresses[i];
        try {
            SocketChannel sChannel = SocketChannel.open();
            allChannels.put(ha, sChannel);
            sChannel.configureBlocking(false);
            sChannel.connect(new InetSocketAddress(ha.getHost(), ha.getPort()));
            remainingChannels.put(ha, sChannel);
        } catch (IOException e) {
            // Cannot connect to one socket ; let's not drop others
            debuglog("Ignoring socket due to connection error: " + ha);
        }
    }

    if (remainingChannels.size() == 0) {
        debuglog("Error: could not connect to any of the XMPP DNS SRV records");
        debuglog("Closing attempted TCP sockets");
        for (SocketChannel sc : allChannels.values()) {
            try {
                sc.close();
            } catch (IOException e) {
            }
        }
        debuglog("All attempted TCP sockets are closed now");
        throw new XMPPConfigurationException("Error: could not connect to any of the XMPP DNS SRV records");
    }

    final long starttime = SystemClock.elapsedRealtime();

    HostAddress goodHostAddress = null;
    while (true) {

        Iterator<Entry<HostAddress, SocketChannel>> iter = remainingChannels.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<HostAddress, SocketChannel> e = iter.next();
            final HostAddress ha = e.getKey();
            final SocketChannel sc = e.getValue();
            try {
                if (sc.finishConnect()) {
                    if (sc.isConnected()) {
                        debuglog("Successful TCP connection to " + ha);
                        iter.remove();
                        if (goodHostAddress != null) {
                            // We already found a host
                            // Pick this better one only if the one we found already was not using the
                            // preferred XMPP port, and the new one does have the preferred XMPP port
                            if (goodHostAddress.getPort() != preferredXMPPPort
                                    && ha.getPort() == preferredXMPPPort) {
                                goodHostAddress = ha;
                                debuglog("Found better host " + goodHostAddress);
                            } else {
                                debuglog("Old host was better: " + goodHostAddress);
                            }
                        } else {
                            goodHostAddress = ha;
                            debuglog("Selecting host " + goodHostAddress);
                        }
                    } else {
                        debuglog("Failed TCP connection to " + ha);
                        iter.remove();
                    }
                }
            } catch (IOException ex) {
                // Error during finishConnect()
                debuglog("TCP connection timeout to " + ha);
                iter.remove();
            }
        }

        final long now = SystemClock.elapsedRealtime();
        if (goodHostAddress != null && goodHostAddress.getPort() == preferredXMPPPort) {
            debuglog("Found responsive XMPP host with preferred port " + preferredXMPPPort);
            break;
        }
        if (remainingChannels.size() == 0) {
            debuglog("No more XMPP hosts to check");
            break;
        }
        if (now > starttime + XMPP_MAX_CONNECT_MILLIS) {
            debuglog("Timeout trying to find responsive XMPP host");
            break;
        }
        if (goodHostAddress != null) {
            if (now > starttime + XMPP_MAX_TRY_PREFERRED_PORT_MILLIS) {
                // XXX: would be better to wait at most N seconds (e.g. 2) AFTER the first successful connection
                // happened (to a non preferred port)
                debuglog("Give up looking for responsive XMPP host with preferred port.");
                break;
            }
            boolean stillWaitingForConnectionWithPreferredPort = false;
            for (HostAddress ha : remainingChannels.keySet()) {
                if (ha.getPort() == preferredXMPPPort) {
                    stillWaitingForConnectionWithPreferredPort = true;
                    break;
                }
            }
            if (!stillWaitingForConnectionWithPreferredPort) {
                debuglog("No more responsive XMPP hosts with preferred port to wait for.");
                break;
            }
        }

        debuglog("Sleeping " + XMPP_POLLING_INTERVAL_MILLIS + "ms while trying to connect to XMPP");
        try {
            Thread.sleep(XMPP_POLLING_INTERVAL_MILLIS);
        } catch (InterruptedException ex) {
            throw new XMPPConfigurationException("Interrupt during Thread.sleep()");
        }
    }

    debuglog("Closing attempted TCP sockets");
    for (SocketChannel sc : allChannels.values()) {
        try {
            sc.close();
        } catch (IOException e) {
        }
    }
    debuglog("All attempted TCP sockets are closed now");

    if (goodHostAddress == null) {
        debuglog("Did not find a good host address and hasfailed: " + hasFailed);
        clearSRVConfig();
        if (hasFailed)
            throw new XMPPConfigurationException("Could not connect to any of the XMPP targets");
        else
            return getSafeXmppConnectionConfiguration(xmppServiceName, email, true);
    }

    debuglog("Using XMPP host " + goodHostAddress);
    xmppConfig.setHosts(new HostAddress[] { goodHostAddress });
    return xmppConfig;
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

private void doAccept(SelectionKey key) {

    SocketChannel clientSocket = null;

    try {//from w  ww  . j a  va  2s .  co  m
        clientSocket = this.listeningSocket.accept();
        if (clientSocket == null) {
            LOG.error("Client socket is null");
            return;
        }
    } catch (IOException ioe) {
        LOG.error(ioe);
        return;
    }

    final IncomingConnection incomingConnection = new IncomingConnection(this.byteBufferedChannelManager,
            clientSocket);
    SelectionKey clientKey = null;
    try {
        clientSocket.configureBlocking(false);
        clientKey = clientSocket.register(this.selector, SelectionKey.OP_READ);
        clientKey.attach(incomingConnection);
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(clientKey, ioe);
    }
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/*from   www.jav a2 s  .com*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:com.springrts.springls.Clients.java

/**
 * Will create new <code>Client</code> object, add it to the 'clients' list
 * and register its socket channel with 'readSelector'.
 * @param sendBufferSize specifies the sockets send buffer size.
 *//*from  w  w w  .ja va2  s . c  o m*/
public Client addNewClient(SocketChannel chan, Selector readSelector, int sendBufferSize) {
    Client client = new Client(chan);
    client.receiveContext(context);
    clients.add(client);

    // register the channel with the selector
    // store a new Client as the Key's attachment
    try {
        chan.configureBlocking(false);
        chan.socket().setSendBufferSize(sendBufferSize);
        // TODO this doesn't seem to have an effect with java.nio
        //chan.socket().setSoTimeout(TIMEOUT_LENGTH);
        client.setSelKey(chan.register(readSelector, SelectionKey.OP_READ, client));
    } catch (IOException ioex) {
        LOG.warn("Failed to establish a connection with a client", ioex);
        killClient(client, "Failed to establish a connection");
        return null;
    }

    return client;
}

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * //from w w  w.j  a  va  2 s. com
 */
@Override
void doAccept(SelectionKey selectionKey) throws IOException {
    ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
    SocketChannel channel = serverChannel.accept();

    if (this.expectedClientContainersMonitor.getCount() == 0) {
        logger.warn("Refusing connection from " + channel.getRemoteAddress() + ", since "
                + this.expectedClientContainers + " ApplicationContainerClients "
                + "identified by 'expectedClientContainers' already connected.");
        this.closeChannel(channel);
    } else {
        channel.configureBlocking(false);
        SelectionKey clientSelectionKey = channel.register(this.selector, SelectionKey.OP_READ);
        if (logger.isInfoEnabled()) {
            logger.info("Accepted conection request from: " + channel.socket().getRemoteSocketAddress());
        }
        if (this.masterSelectionKey != null) {
            this.containerDelegates.put(clientSelectionKey,
                    new ContainerDelegateImpl(clientSelectionKey, this));
        } else {
            this.masterSelectionKey = clientSelectionKey;
            this.masterSelectionKey.attach(true);
        }
        this.expectedClientContainersMonitor.countDown();
    }
}

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

/**
 * Accept an icoming connection/*from www.j ava 2s .co  m*/
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Accept the next incoming connection.//from  w  w  w .  j av  a  2 s .c o m
 *
 * <p>
 * When a new peer connects to this service, wait for it to send its
 * handshake. We then parse and check that the handshake advertises the
 * torrent hash we expect, then reply with our own handshake.
 * </p>
 *
 * <p>
 * If everything goes according to plan, notify the
 * <code>IncomingConnectionListener</code>s with the connected socket and
 * the parsed peer ID.
 * </p>
 *
 * @param client The accepted client's socket channel.
 */
private void accept(SocketChannel client) throws IOException, SocketTimeoutException {
    try {
        logger.debug("New incoming connection, waiting for handshake...");
        Handshake hs = this.validateHandshake(client, null);
        int sent = this.sendHandshake(client);
        logger.trace("Replied to {} with handshake ({} bytes).", this.socketRepr(client), sent);

        // Go to non-blocking mode for peer interaction
        client.configureBlocking(false);
        client.socket().setSoTimeout(CLIENT_KEEP_ALIVE_MINUTES * 60 * 1000);
        this.fireNewPeerConnection(client, hs.getPeerId());
    } catch (ParseException pe) {
        logger.info("Invalid handshake from {}: {}", this.socketRepr(client), pe.getMessage());
        IOUtils.closeQuietly(client);
    } catch (IOException ioe) {
        logger.warn("An error occured while reading an incoming " + "handshake: {}", ioe.getMessage());
        if (client.isConnected()) {
            IOUtils.closeQuietly(client);
        }
    }
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Ouverture de la socket.//www.  j  a  va 2s  .c  o  m
 *
 * @return la socket
 * @throws ClamAVException
 *             the clam av exception
 */
private SocketChannel openSocket() throws ClamAVException {

    SocketChannel channel = null;
    try {
        // Rcuperation de la socket depuis le pool
        channel = this.socketPool.borrowObject();

        if (!channel.isOpen()) {
            channel = SocketChannel.open();
        }
        if (!channel.isConnected()) {
            channel.configureBlocking(true);
            channel.connect(new InetSocketAddress(this.clamAVServer, this.clamAVPort));
        }
    } catch (final Exception e) {
        ClamAVCheckService.LOGGER.error("Unable to borrow socket from pool", e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    }

    return channel;
}

From source file:Proxy.java

void _handleConnection(final SocketChannel in_channel, final SocketChannel out_channel) throws Exception {
    executor.execute(new Runnable() {
        public void run() {
            Selector sel = null;/*www .  j av a 2s  .co m*/
            SocketChannel tmp;
            Set ready_keys;
            SelectionKey key;
            ByteBuffer transfer_buf = ByteBuffer.allocate(BUFSIZE);

            try {
                sel = Selector.open();
                in_channel.configureBlocking(false);
                out_channel.configureBlocking(false);
                in_channel.register(sel, SelectionKey.OP_READ);
                out_channel.register(sel, SelectionKey.OP_READ);

                while (sel.select() > 0) {
                    ready_keys = sel.selectedKeys();
                    for (Iterator it = ready_keys.iterator(); it.hasNext();) {
                        key = (SelectionKey) it.next();
                        it.remove(); // remove current entry (why ?)
                        tmp = (SocketChannel) key.channel();
                        if (tmp == null) {
                            log("Proxy._handleConnection()", "attachment is null, continuing");
                            continue;
                        }
                        if (key.isReadable()) { // data is available to be read from tmp
                            if (tmp == in_channel) {
                                // read all data from in_channel and forward it to out_channel (request)
                                if (relay(tmp, out_channel, transfer_buf) == false)
                                    return;
                            }
                            if (tmp == out_channel) {
                                // read all data from out_channel and forward it 
                                // to in_channel (response)
                                if (relay(tmp, in_channel, transfer_buf) == false)
                                    return;
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                close(sel, in_channel, out_channel);
            }
        }
    });
}