Example usage for java.nio.channels SocketChannel close

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

Introduction

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

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.buaa.cfs.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 *
 * @param channel  - this should be a {@link SelectableChannel}
 * @param endpoint//  ww  w.j  av  a  2s .  com
 *
 * @throws IOException
 * @see SocketChannel#connect(SocketAddress)
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (Time.now() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

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.");
    }//from  www.jav  a 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:org.commoncrawl.io.internal.NIOServerTCPSocket.java

public void acceptable() {
    if (_listener != null) {

        SocketChannel newClientChannel = null;
        try {/*from  ww  w  .  jav a 2s.  c  o m*/
            newClientChannel = _channel.accept();
            // set socket options 
            setClientSocketOptions(newClientChannel);
            // allocate a new NIOClientTCPSocket object ... 
            NIOClientTCPSocket newSocketObj = new NIOClientTCPSocket(newClientChannel);
            // inform the listener of the event
            _listener.Accepted(newSocketObj);
        } catch (IOException e) {
            if (newClientChannel != null) {
                try {
                    newClientChannel.close();
                } catch (IOException e2) {
                    throw new RuntimeException(e2);
                }
            }
            throw new RuntimeException(e);
        }
    }

}

From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 * /*  w w w  .ja  va 2  s .c  o m*/
 * @see SocketChannel#connect(SocketAddress)
 * @param channel
 *        - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

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

/**
 * Reports a problem which occurred while establishing the underlying TCP connection to this outgoing connection
 * object. Depending on the number of connection retries left, this method will either try to reestablish the TCP
 * connection or report an I/O error to all tasks which have queued envelopes for this connection. In the latter
 * case all queued envelopes will be dropped and all included buffers will be freed.
 * <p>//www.  ja v  a 2 s  .co  m
 * This method should only be called by the {@link OutgoingConnectionThread} object.
 * 
 * @param ioe
 *        thrown if an error occurs while reseting the underlying TCP connection
 */
public void reportConnectionProblem(IOException ioe) {

    // First, write exception to log
    final long currentTime = System.currentTimeMillis();
    if (currentTime - this.timstampOfLastRetry >= RETRYINTERVAL) {
        LOG.error("Cannot connect to " + this.remoteReceiver + ", " + this.retriesLeft + " retries left");
    }

    synchronized (this.queuedEnvelopes) {

        if (this.selectionKey != null) {

            final SocketChannel socketChannel = (SocketChannel) this.selectionKey.channel();
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    LOG.debug("Error while trying to close the socket channel to " + this.remoteReceiver);
                }
            }

            this.selectionKey.cancel();
            this.selectionKey = null;
            this.isConnected = false;
            this.isSubscribedToWriteEvent = false;
        }

        if (hasRetriesLeft(currentTime)) {
            this.connectionThread.triggerConnect(this);
            this.isConnected = true;
            this.isSubscribedToWriteEvent = true;
            return;
        }

        // Error is fatal
        LOG.error(ioe);

        // Notify source of current envelope and release buffer
        if (this.currentEnvelope != null) {
            if (this.currentEnvelope.getBuffer() != null) {
                this.currentEnvelope.getBuffer().recycleBuffer();
                this.currentEnvelope = null;
            }
        }

        // Notify all other tasks which are waiting for data to be transmitted
        final Iterator<TransferEnvelope> iter = this.queuedEnvelopes.iterator();
        while (iter.hasNext()) {
            final TransferEnvelope envelope = iter.next();
            iter.remove();
            // Recycle the buffer inside the envelope
            if (envelope.getBuffer() != null) {
                envelope.getBuffer().recycleBuffer();
            }
        }

        this.queuedEnvelopes.clear();
    }
}

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

public void disconnect(SocketChannel socketChannel) {

    if (socketChannel.isConnected() && socketChannel.isOpen()) {
        processOutput(socketChannel);/*w w w .j  av a2s.  c om*/
    }
    LoggerFactory.getLogger(Network.class)
            .info("Disconnecting {local=" + socketChannel.socket().getLocalSocketAddress() + " remote="
                    + socketChannel.socket().getRemoteSocketAddress() + "}\n");
    fireEvent(NetworkDisconnectEvent.class, socketChannel);

    try {
        socketChannel.close();
    } catch (IOException e) {
        LoggerFactory.getLogger(this.getClass()).warn("Exception", e);
    }
}

From source file:morphy.service.SocketConnectionService.java

protected void disposeSocketChannel(SocketChannel channel) {
    if (channel.isConnected()) {
        try {//  ww  w .ja  v a  2  s.c  om
            channel.close();
        } catch (Throwable t) {
        }
    }
    socketToSession.remove(channel.socket());
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected void sendTo(int aPort, String anEncodedMessage) {
    SocketChannel socketChannel = null;

    try {/*from  w  w w  . jav  a  2s  .c o m*/
        socketChannel = SocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), aPort);
        socketChannel.connect(address);
        socketChannel.write(ByteBuffer.wrap(anEncodedMessage.getBytes()));
        logger.debug("Sent: {}", anEncodedMessage);

    } catch (IOException e) {
        logger.error("Failed to send because: {}: Continuing...", e.getMessage(), e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                logger.error("Failed to close client socket because: {}: Continuing...", e.getMessage(), e);
            }
        }
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(timeOut = 15000)
public void testTunnelToEchoServer() throws IOException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {// w w w.j a v  a 2 s .  co  m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        String response = readFromSocket(client);
        client.close();

        assertEquals(response, "Knock Knock\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(timeOut = 15000)
public void testTunnelToDelayedEchoServer() throws IOException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", delayedDoubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {//from   w w  w . j av  a 2s. c  o  m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        String response = readFromSocket(client);
        client.close();

        assertEquals(response, "Knock Knock\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}