Search in sources :

Example 31 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project ignite by apache.

the class FileDownloader method download.

/**
 */
public void download(GridFutureAdapter<?> fut) {
    this.finishFut = fut;
    final ServerSocketChannel ch = serverChannel;
    fut.listen(new IgniteInClosureX<IgniteInternalFuture<?>>() {

        @Override
        public void applyx(IgniteInternalFuture<?> future) throws IgniteCheckedException {
            try {
                if (log != null && log.isInfoEnabled())
                    log.info("Server socket closed " + ch.getLocalAddress());
                ch.close();
            } catch (Exception ex) {
                U.error(log, "Fail close socket.", ex);
                throw new IgniteCheckedException(ex);
            }
        }
    });
    FileChannel writeChannel = null;
    SocketChannel readChannel = null;
    try {
        File f = new File(path.toUri().getPath());
        if (f.exists())
            f.delete();
        File cacheWorkDir = f.getParentFile();
        if (!cacheWorkDir.exists())
            cacheWorkDir.mkdir();
        writeChannel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
        initFut.onDone();
        readChannel = serverChannel.accept();
        long pos = 0;
        long size = this.size.get();
        while (size == -1 || pos < size) {
            pos += writeChannel.transferFrom(readChannel, pos, CHUNK_SIZE);
            if (size == -1)
                size = this.size.get();
        }
    } catch (IOException ex) {
        initFut.onDone(ex);
        fut.onDone(ex);
    } finally {
        try {
            if (writeChannel != null)
                writeChannel.close();
        } catch (IOException ex) {
            throw new IgniteException("Could not close file: " + path);
        }
        try {
            if (readChannel != null)
                readChannel.close();
        } catch (IOException ex) {
            throw new IgniteException("Could not close socket");
        }
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) FileChannel(java.nio.channels.FileChannel) IOException(java.io.IOException) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) File(java.io.File) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 32 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project ambry by linkedin.

the class Processor method acceptConnection.

protected SocketChannel acceptConnection(SelectionKey key) throws SocketException, IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
    serverSocketChannel.socket().setReceiveBufferSize(recvBufferSize);
    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.socket().setTcpNoDelay(true);
    socketChannel.socket().setSendBufferSize(sendBufferSize);
    logger.trace("Accepted connection from {} on {}. sendBufferSize " + "[actual|requested]: [{}|{}] recvBufferSize [actual|requested]: [{}|{}]", socketChannel.socket().getInetAddress(), socketChannel.socket().getLocalSocketAddress(), socketChannel.socket().getSendBufferSize(), sendBufferSize, socketChannel.socket().getReceiveBufferSize(), recvBufferSize);
    return socketChannel;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 33 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project ambry by linkedin.

the class Processor method openServerSocket.

/*
   * Create a server socket to listen for connections on.
   */
private ServerSocketChannel openServerSocket(int port) throws IOException {
    InetSocketAddress address = new InetSocketAddress(port);
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    serverChannel.socket().bind(address);
    logger.info("Awaiting socket connections on {}:{}", address.getHostName(), port);
    return serverChannel;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 34 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project nifi by apache.

the class SocketChannelDispatcher method run.

@Override
public void run() {
    while (!stopped) {
        try {
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met", new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}", new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);
                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();
                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);
                            switch(clientAuth) {
                                case REQUIRED:
                                    sslEngine.setNeedClientAuth(true);
                                    break;
                                case WANT:
                                    sslEngine.setWantClientAuth(true);
                                    break;
                                case NONE:
                                    sslEngine.setNeedClientAuth(false);
                                    sslEngine.setWantClientAuth(false);
                                    break;
                            }
                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }
                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer, sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events, logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events, logger);
                        }
                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SSLSocketChannel(org.apache.nifi.remote.io.socket.ssl.SSLSocketChannel) SSLEngine(javax.net.ssl.SSLEngine) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 35 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project nifi by apache.

the class SocketChannelDispatcher method open.

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;
    executor = Executors.newFixedThreadPool(maxConnections);
    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    if (maxBufferSize > 0) {
        serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer");
        }
    }
    serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));
    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Aggregations

ServerSocketChannel (java.nio.channels.ServerSocketChannel)274 SocketChannel (java.nio.channels.SocketChannel)156 InetSocketAddress (java.net.InetSocketAddress)128 IOException (java.io.IOException)96 ByteBuffer (java.nio.ByteBuffer)53 SelectionKey (java.nio.channels.SelectionKey)41 ServerSocket (java.net.ServerSocket)37 Test (org.junit.Test)27 Socket (java.net.Socket)24 ClosedChannelException (java.nio.channels.ClosedChannelException)22 Selector (java.nio.channels.Selector)22 ClosedSelectorException (java.nio.channels.ClosedSelectorException)15 InetAddress (java.net.InetAddress)14 CancelledKeyException (java.nio.channels.CancelledKeyException)11 EOFException (java.io.EOFException)8 SocketException (java.net.SocketException)8 BindException (java.net.BindException)7 SocketAddress (java.net.SocketAddress)7 Test (org.junit.jupiter.api.Test)7 OutgoingPacket (com.twitter.heron.common.network.OutgoingPacket)6