Example usage for java.nio.channels SocketChannel open

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

Introduction

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

Prototype

public static SocketChannel open() throws IOException 

Source Link

Document

Opens a socket channel.

Usage

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

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from   w w w.  j a v  a  2  s  .c o m
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }/*  ww w. ja v  a2s.c o m*/
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:com.hurence.logisland.redis.service.ITRedisKeyValueCacheClientService.java

private int getAvailablePort() throws IOException {
    try (SocketChannel socket = SocketChannel.open()) {
        socket.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        socket.bind(new InetSocketAddress("localhost", 0));
        return socket.socket().getLocalPort();
    }/*from   ww w.j  a  va 2  s  .c o m*/
}

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

/**
 * /*from www. j  a va  2s.com*/
 * @param address
 * @param server
 */
public AbstractSocketHandler(InetSocketAddress address, boolean server, Runnable onDisconnectTask) {
    Assert.notNull(address);
    this.onDisconnectTask = onDisconnectTask;
    this.address = address;
    this.executor = Executors.newCachedThreadPool();
    this.listenerTask = new ListenerTask();
    this.readingBuffer = ByteBuffer.allocate(16384);
    this.bufferPoll = new ByteBufferPool();
    try {
        this.rootChannel = server ? ServerSocketChannel.open() : SocketChannel.open();
        if (logger.isDebugEnabled()) {
            logger.debug("Created instance of " + this.getClass().getSimpleName());
        }
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create an instance of the ApplicationContainerClient", e);
    }
    this.thisClass = this.getClass();
    this.lifeCycleLatch = new CountDownLatch(1);
}

From source file:co.elastic.tealess.SSLChecker.java

private SSLReport check(InetSocketAddress address, String name, long timeout) {
    SSLReport sslReport = new SSLReport();
    sslReport.setSSLContextBuilder(ctxbuilder);
    sslReport.setSSLContext(ctx);/*ww  w.  ja  va2s  . com*/
    sslReport.setHostname(name);
    sslReport.setAddress(address);
    sslReport.setTimeout(timeout);

    logger.debug("Trying {} (expected hostname {})", address, name);
    SocketChannel socket;
    try {
        socket = SocketChannel.open();
        socket.configureBlocking(false);
    } catch (IOException e) {
        sslReport.setFailed(e);
        return sslReport;
    }

    checkConnect(sslReport, socket, timeout);
    if (sslReport.getException() != null) {
        return sslReport;
    }

    checkHandshake(sslReport, socket);
    if (sslReport.getException() != null) {
        return sslReport;
    }

    checkHostnameVerification(sslReport);
    return sslReport;
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();// www  . jav  a2 s  .  c om
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

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

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

    try {/*  w  w w.  j  a va  2  s  . co  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:org.apache.gobblin.tunnel.TunnelTest.java

@Test(enabled = false)
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();//from   w  w  w.  j  av  a2  s . co  m
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

From source file:org.commoncrawl.io.NIOClientTCPSocket.java

public NIOClientTCPSocket(InetSocketAddress localAddress, NIOClientSocketListener socketListener)
        throws IOException {
    _socketType = SocketType.Outgoing;//from www. j a v a  2  s  . c o m
    _channel = SocketChannel.open();
    if (localAddress != null) {
        InetSocketAddress modifiedLocalAddress = new InetSocketAddress(localAddress.getAddress(), 0);
        // System.out.println("Binding To Local Address:" +
        // modifiedLocalAddress.getAddress());
        // LOG.info(this + "Binding To Local Address:" +
        // modifiedLocalAddress.getAddress());
        _channel.socket().bind(modifiedLocalAddress);
    }
    _localAddress = (InetSocketAddress) _channel.socket().getLocalSocketAddress();
    setClientSocketOptions(_channel);
    _listener = socketListener;

}

From source file:com.facebook.infrastructure.net.TcpConnection.java

private void setupChannel() throws IOException {
    socketChannel_ = SocketChannel.open();
    socketChannel_.configureBlocking(false);
    logger_.info("Opening socketchannel to " + remoteEp_.getInetAddress() + "(" + socketChannel_ + ")");
    if (!socketChannel_.connect(remoteEp_.getInetAddress())) {
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_CONNECT);
    } else {//from w ww  .  j  a  v a2 s .  c  o  m
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_READ);
        connected_.set(true);
    }
}