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:gridool.util.net.PoolableSocketChannelFactory.java

private static SocketChannel createSocketChannel(final SocketAddress sockAddr, final boolean blocking,
        final int rcvbufSize) {
    final SocketChannel ch;
    try {//from   w  ww.  j  ava  2s  . c  o m
        ch = SocketChannel.open();
        ch.configureBlocking(blocking);
    } catch (IOException e) {
        LOG.error("Failed to open SocketChannel.", e);
        throw new IllegalStateException(e);
    }
    final Socket sock = ch.socket();
    if (rcvbufSize != -1) {
        try {
            sock.setReceiveBufferSize(rcvbufSize);
        } catch (SocketException e) {
            LOG.error("Failed to setReceiveBufferSize.", e);
            throw new IllegalStateException(e);
        }
    }
    try {
        ch.connect(sockAddr);
    } catch (IOException e) {
        LOG.error("Failed to connect socket: " + sockAddr, e);
        throw new IllegalStateException(e);
    }
    return ch;
}

From source file:org.apache.nifi.processor.util.put.sender.SocketChannelSender.java

@Override
public void open() throws IOException {
    if (channel == null) {
        channel = SocketChannel.open();
        channel.configureBlocking(false);

        if (maxSendBufferSize > 0) {
            channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize);
            final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF);
            if (actualSendBufSize < maxSendBufferSize) {
                logger.warn("Attempted to set Socket Send Buffer Size to " + maxSendBufferSize
                        + " bytes but could only set to " + actualSendBufSize + "bytes. You may want to "
                        + "consider changing the Operating System's maximum receive buffer");
            }/*w  w  w. j av  a  2 s . c o m*/
        }
    }

    if (!channel.isConnected()) {
        final long startTime = System.currentTimeMillis();
        final InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(host), port);

        if (!channel.connect(socketAddress)) {
            while (!channel.finishConnect()) {
                if (System.currentTimeMillis() > startTime + timeout) {
                    throw new SocketTimeoutException("Timed out connecting to " + host + ":" + port);
                }

                try {
                    Thread.sleep(50L);
                } catch (final InterruptedException e) {
                }
            }
        }

        socketChannelOutput = new SocketChannelOutputStream(channel);
        socketChannelOutput.setTimeout(timeout);
    }
}

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

public NIOClientTCPSocket(InetSocketAddress localAddress, NIOClientSocketListener socketListener)
        throws IOException {
    _socketType = SocketType.Outgoing;//from   ww  w  . j  av  a 2 s .  co 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:gridool.communication.transport.tcp.GridNioClient.java

public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException {
    final SocketChannel channel;
    try {//  www.ja v a 2 s  .c om
        channel = SocketChannel.open();
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }
    final Socket socket = channel.socket();
    try {
        SocketUtils.openSocket(socket, sockAddr, 0, 2000L, 3);
    } catch (IOException e) {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }

    final ByteBuffer buf = toBuffer(msg);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining()
                + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']');
    }
    final int written;
    try {
        written = NIOUtils.countingWriteFully(channel, buf);
        NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN)
    } catch (IOException ioe) {
        final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr
                + ']';
        LOG.error(errmsg, ioe);
        throw new GridException(errmsg, ioe);
    } catch (Throwable e) {
        LOG.fatal(e.getMessage(), e);
        throw new GridException("Unexpected exception was caused", e);
    } finally {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr
                + "]");
    }
}

From source file:gridool.communication.transport.tcp.GridNonBlockingClient.java

public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException {
    final SocketChannel channel;
    try {//  ww w .  j av  a 2s  . co  m
        channel = SocketChannel.open();
        channel.configureBlocking(false);
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }
    final Socket socket = channel.socket();
    try {
        socket.connect(sockAddr);
        // wait for connect succeeds
        while (!channel.finishConnect()) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                ;
            }
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }

    final ByteBuffer buf = toBuffer(msg);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining()
                + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']');
    }
    final int written;
    try {
        written = NIOUtils.countingWriteFully(channel, buf);
        NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN)
    } catch (IOException ioe) {
        final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr
                + ']';
        LOG.error(errmsg, ioe);
        throw new GridException(errmsg, ioe);
    } catch (Throwable e) {
        LOG.fatal(e.getMessage(), e);
        throw new GridException("Unexpected exception was caused", e);
    } finally {
        NetUtils.closeQuietly(socket);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr
                + "]");
    }
}

From source file:com.byteatebit.nbserver.simple.client.SimpleNbClient.java

public void tcpConnect(String remoteHost, int remotePort, IClientSocketChannelHandler socketChannelHandler,
        long timeout) throws IOException {
    if (!initialized.get())
        throw new IllegalStateException("SimpleNbClient must first be initialized via init()");
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort);
    INbContext nbContext = new NbContext(simpleNbService.getSelectorRegistrarBalancer().getSelectorRegistrar(),
            simpleNbService.getScheduler());
    IOTask connectTask = (selectionKey) -> {
        boolean connectionFinished = false;
        try {/* ww  w  . j  a va2s  .  c o m*/
            connectionFinished = socketChannel.finishConnect();
        } catch (IOException e) {
            LOG.error("Could not complete socket connection.", e);
        }
        if (!connectionFinished) {
            LOG.error("Could not complete socket connection.  Closing socket channel");
            selectionKey.cancel();
            IOUtils.closeQuietly(socketChannel);
            socketChannelHandler.connectFailed(remoteHost, remotePort);
            return;
        }
        selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_CONNECT);
        socketChannelHandler.accept(nbContext, socketChannel);
    };
    IOTimeoutTask timeoutTask = (selectionKey, ops) -> {
        LOG.error("Connect attempt timed out after " + timeout + " ms");
        selectionKey.cancel();
        IOUtils.closeQuietly(socketChannel);
        socketChannelHandler.connectFailed(remoteHost, remotePort);
    };
    nbContext.register(socketChannel, SelectionKey.OP_CONNECT, connectTask, timeoutTask, timeout);
    socketChannel.connect(address);
}

From source file:org.apache.james.CassandraConfTest.java

@Before
public void setUp() throws IOException {
    socketChannel = SocketChannel.open();
}

From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java

@SuppressWarnings("unchecked")
protected INioSession __doSessionCreate(IClientCfg cfg) throws IOException {
    SocketChannel _channel = SocketChannel.open();
    _channel.configureBlocking(false);//from w w  w . jav  a 2  s . c  o m
    _channel.socket().setReuseAddress(true);
    _channel.connect(new InetSocketAddress(cfg.getRemoteHost(), cfg.getPort()));
    __channel = _channel;
    return new NioSession(this, _channel);
}

From source file:edu.tsinghua.lumaqq.qq.net.AbstractProxy.java

/**
 * //from  ww w .  j a  v a 2s  . com
 * 
 * @throws IOException
 */
public AbstractProxy(IProxyHandler handler) throws IOException {
    this.handler = handler;
    buffer = ByteBuffer.allocateDirect(300);
    username = password = "";
    connected = false;
    udp = false;

    socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
}

From source file:edu.tsinghua.lumaqq.qq.net.TCPPort.java

/**
 * ?TCPPort. /*from w w w  . j  a  va2  s .  co  m*/
 * 
 * @param address ?.
 * @throws IOException ?/??/?.
 */
public TCPPort(IConnectionPolicy policy, InetSocketAddress address) throws IOException {
    super(policy);
    channel = SocketChannel.open();
    channel.configureBlocking(false);
    this.remoteAddress = address;
    remoteClosed = false;
}