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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(expectedExceptions = IOException.class)
public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient()
        throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    final int nonExistentPort = 54321; // hope this doesn't exist!
    Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort());
    try {/*from   w  ww .j  a  v a 2s . c o m*/
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.configureBlocking(true);
        client.connect(new InetSocketAddress("localhost", tunnelPort));
        // Might have to write multiple times before connection error propagates back from proxy through tunnel to client
        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
            Thread.sleep(100);
        }
        String response1 = readFromSocket(client);
        LOG.info(response1);

        client.close();

    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
        assertEquals(proxyServer.getNumConnects(), 1);
    }
}

From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(enabled = false, expectedExceptions = IOException.class)
public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient()
        throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    final int nonExistentPort = 54321; // hope this doesn't exist!
    Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort());
    try {//w w  w.j ava  2s . co  m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.configureBlocking(true);
        client.connect(new InetSocketAddress("localhost", tunnelPort));
        // Might have to write multiple times before connection error propagates back from proxy through tunnel to client
        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
            Thread.sleep(100);
        }
        String response1 = readFromSocket(client);
        LOG.info(response1);

        client.close();

    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
        assertEquals(proxyServer.getNumConnects(), 1);
    }
}

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

protected String receive() {
    SocketChannel socketChannel = null;

    try {/*w  w w.  j  a v  a 2 s.  com*/
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.cloudata.core.commitlog.CommitLogClient.java

private TransactionData[] readDataFrom(Method readMethod, int index, String tabletName) throws IOException {
    int port = -1;
    int replicaCount = rpcUtil.getMultiRpcCount();

    for (int count = 0; count < replicaCount; count++) {
        try {// w  w  w  . j a v  a 2  s  . co m
            port = (Integer) rpcUtil.singleCall(readMethod, index, tabletName);
            if (port > 0) {
                break;
            }
        } catch (IOException e) {
            LOG.info("Exception in reading commit log data : " + e);
        }

        if (++index % replicaCount == 0) {
            index = 0;
        }
    }

    if (port < 0) {
        return null;
    }

    SocketChannel socketChannel = SocketChannel.open();
    List<TransactionData> txDataList = null;
    try {
        socketChannel.connect(new InetSocketAddress(rpcUtil.getAddressAt(index), port));
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(socketChannel.socket().getInputStream(), 8192));

        txDataList = readTxDataFrom(tabletName, dis);
    } finally {
        socketChannel.socket().close();
        socketChannel.close();
    }

    return txDataList.toArray(new TransactionData[0]);
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void sendGarbageTest() throws IOException {

    InetSocketAddress socketAddress = new InetSocketAddress(PORT);
    SocketChannel channel = SocketChannel.open(socketAddress);
    channel.write(ByteBuffer.wrap(new byte[] { 1, 1, 1, 1 } // garbage
    ));//from  ww  w .  j a v a  2s  .  c  om
    channel.close();
}

From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*///from w  w  w. jav  a 2  s. c o m
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        //dataSocket.configureBlocking(false);
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {
        System.err.println("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        System.err.println("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

From source file:edu.hawaii.soest.kilonalu.adcp.ADCPSource.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*///from   w  w w . java2 s.  co  m
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {
        System.err.println("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        System.err.println("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

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

/**
 * Reports an I/O error which occurred while writing data to the TCP connection. As a result of the I/O error the
 * connection is closed and the interest keys are canceled. Moreover, the task which queued the currently
 * transmitted transfer envelope is notified about the error and the current envelope is dropped. If the current
 * envelope contains a buffer, the buffer is freed.
 * <p>//from   w  w w  . ja v a 2 s  . c  o  m
 * This method should only be called by the {@link OutgoingConnectionThread} object.
 * 
 * @param ioe
 *        thrown if an error occurs while reseting the connection
 */
public void reportTransmissionProblem(IOException ioe) {

    final SocketChannel socketChannel = (SocketChannel) this.selectionKey.channel();

    // First, write exception to log
    if (this.currentEnvelope != null) {
        LOG.error("The connection between " + socketChannel.socket().getLocalAddress() + " and "
                + socketChannel.socket().getRemoteSocketAddress()
                + " experienced an IOException for transfer envelope "
                + this.currentEnvelope.getSequenceNumber());
    } else {
        LOG.error("The connection between " + socketChannel.socket().getLocalAddress() + " and "
                + socketChannel.socket().getRemoteSocketAddress() + " experienced an IOException");
    }

    // Close the connection and cancel the interest key
    synchronized (this.queuedEnvelopes) {
        try {
            LOG.debug("Closing connection to " + socketChannel.socket().getRemoteSocketAddress());
            socketChannel.close();
        } catch (IOException e) {
            LOG.debug("An error occurred while responding to an IOException");
            LOG.debug(e);
        }

        this.selectionKey.cancel();

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

        // Trigger new connection if there are more envelopes to be transmitted
        if (this.queuedEnvelopes.isEmpty()) {
            this.isConnected = false;
            this.isSubscribedToWriteEvent = false;
        } else {
            this.connectionThread.triggerConnect(this);
            this.isConnected = true;
            this.isSubscribedToWriteEvent = true;
        }

        // We must assume the current envelope is corrupted so we notify the task which created it.
        if (this.currentEnvelope != null) {
            if (this.currentEnvelope.getBuffer() != null) {
                this.currentEnvelope.getBuffer().recycleBuffer();
                this.currentEnvelope = null;
            }
        }
    }
}

From source file:edu.hawaii.soest.kilonalu.tchain.TChainSource.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*/// w w w .j  av  a2  s .  co m
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        Socket tcpSocket = dataSocket.socket();
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setReceiveBufferSize(40);
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {
        System.err.println("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        System.err.println("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

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

/** Check for incoming messages */
private void readIncomingMessages() {

    Client client = null;//from www.j a v a  2s.  co m
    try {
        // non-blocking select, returns immediately regardless of
        // how many keys are ready
        readSelector.selectNow();

        // fetch the keys
        Set<SelectionKey> readyKeys = readSelector.selectedKeys();

        // run through the keys and process each one
        while (!readyKeys.isEmpty()) {
            SelectionKey key = readyKeys.iterator().next();
            readyKeys.remove(key);
            SocketChannel channel = (SocketChannel) key.channel();
            client = (Client) key.attachment();
            if (client.isHalfDead()) {
                continue;
            }
            readBuffer.clear();

            client.setTimeOfLastReceive(System.currentTimeMillis());

            // read from the channel into our buffer
            long nBytes = channel.read(readBuffer);
            client.addReceived(nBytes);

            // basic anti-flood protection
            FloodProtectionService floodProtection = getContext().getService(FloodProtectionService.class);
            if ((floodProtection != null) && floodProtection.isFlooding(client)) {
                continue;
            }

            // check for end-of-stream
            if (nBytes == -1) {
                LOG.debug("Socket disconnected - killing client");
                channel.close();
                // this will also close the socket channel
                getContext().getClients().killClient(client);
            } else {
                // use a CharsetDecoder to turn those bytes into a string
                // and append it to the client's StringBuilder
                readBuffer.flip();
                String str = getContext().getServer().getAsciiDecoder().decode(readBuffer).toString();
                readBuffer.clear();
                client.appendToRecvBuf(str);

                // TODO move this to Client#appendToRecvBuf(String)
                // check for a full line
                String line = client.readLine();
                while (line != null) {
                    executeCommandWrapper(line, client);

                    if (!client.isAlive()) {
                        // in case the client was killed within the
                        // executeCommand() method
                        break;
                    }
                    line = client.readLine();
                }
            }
        }
    } catch (IOException ioex) {
        LOG.info("exception during select(): possibly due to force disconnect. Killing the client ...");
        if (client != null) {
            getContext().getClients().killClient(client, "Quit: connection lost");
        }
        LOG.debug("... the exception was:", ioex);
    }
}