Example usage for java.nio.channels ServerSocketChannel configureBlocking

List of usage examples for java.nio.channels ServerSocketChannel configureBlocking

Introduction

In this page you can find the example usage for java.nio.channels ServerSocketChannel configureBlocking.

Prototype

public final SelectableChannel configureBlocking(boolean block) throws IOException 

Source Link

Document

Adjusts this channel's blocking mode.

Usage

From source file:jp.queuelinker.system.net.SelectorThread.java

public int openServerSocket(final InetSocketAddress bindAddress, final SelectorCallBack callBack)
        throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);
    serverChannel.socket().setReuseAddress(true);
    serverChannel.socket().bind(bindAddress);
    return addSocketChannel(serverChannel, callBack);
}

From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java

/**
 * jmx:managed-operation//from w ww . j  a v  a 2  s.  c  om
 */
@Override
public void init() throws IOException {
    // Find a port.
    if (startPort == 0) {
        port = 0;
        LoggerUtils.getLogger().info("JK: ajp13 disabling channelNioSocket");
        running = true;
        return;
    }
    if (maxPort < startPort) {
        maxPort = startPort;
    }
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    for (int i = startPort; i <= maxPort; i++) {
        try {
            InetSocketAddress iddr = null;
            if (inet == null) {
                iddr = new InetSocketAddress(i);
            } else {
                iddr = new InetSocketAddress(inet, i);
            }
            sSocket = ssc.socket();
            sSocket.bind(iddr);
            port = i;
            break;
        } catch (IOException ex) {

            LoggerUtils.getLogger().info("Port busy " + i + " " + ex.toString());
            sSocket = null;
        }
    }

    if (sSocket == null) {
        LoggerUtils.getLogger().log(Level.SEVERE, "Can't find free port " + startPort + " " + maxPort);
        return;
    }

    LoggerUtils.getLogger().info("JK: ajp13 listening on " + getAddress() + ":" + port);

    selector = Utils.openSelector();
    ssc.register(selector, SelectionKey.OP_ACCEPT);
    // If this is not the base port and we are the 'main' channleSocket and
    // SHM didn't already set the localId - we'll set the instance id
    if ("channelNioSocket".equals(name) && port != startPort && (wEnv.getLocalId() == 0)) {
        wEnv.setLocalId(port - startPort);
    }

    // XXX Reverse it -> this is a notification generator !!
    if (next == null && wEnv != null) {
        if (nextName != null) {
            setNext(wEnv.getHandler(nextName));
        }
        if (next == null) {
            next = wEnv.getHandler("dispatch");
        }
        if (next == null) {
            next = wEnv.getHandler("request");
        }
    }
    JMXRequestNote = wEnv.getNoteId(WorkerEnv.ENDPOINT_NOTE, "requestNote");
    running = true;

    // Run a thread that will accept connections.
    // XXX Try to find a thread first - not sure how...
    if (this.domain != null) {
        try {
            tpOName = new ObjectName(domain + ":type=ThreadPool,name=" + getChannelName());

            Registry.getRegistry(null, null).registerComponent(tp, tpOName, null);

            rgOName = new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getChannelName());
            Registry.getRegistry(null, null).registerComponent(global, rgOName, null);
        } catch (Exception e) {
            LoggerUtils.getLogger().log(Level.SEVERE, "Can't register threadpool");
        }
    }

    tp.start();
    Poller pollAjp = new Poller();
    tp.runIt(pollAjp);
}

From source file:Proxy.java

public void start() throws Exception {
    Map.Entry entry;//w  ww.j  av a  2s  . com
    Selector selector;
    ServerSocketChannel sock_channel;
    MyInetSocketAddress key, value;

    if (remote != null && local != null)
        mappings.put(new InetSocketAddress(local, local_port), new InetSocketAddress(remote, remote_port));

    if (mapping_file != null) {
        try {
            populateMappings(mapping_file);
        } catch (Exception ex) {
            log("Failed reading " + mapping_file);
            throw ex;
        }
    }

    log("\nProxy started at " + new java.util.Date());

    if (verbose) {
        log("\nMappings:\n---------");
        for (Iterator it = mappings.entrySet().iterator(); it.hasNext();) {
            entry = (Map.Entry) it.next();
            log(toString((InetSocketAddress) entry.getKey()) + " <--> "
                    + toString((InetSocketAddress) entry.getValue()));
        }
        log("\n");
    }

    // 1. Create a Selector
    selector = Selector.open();

    // Create a thread pool (Executor)
    executor = new ThreadPoolExecutor(MIN_THREAD_POOL_SIZE, MAX_THREAD_POOL_SIZE, 30000, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(1000));

    for (Iterator it = mappings.keySet().iterator(); it.hasNext();) {
        key = (MyInetSocketAddress) it.next();
        value = (MyInetSocketAddress) mappings.get(key);

        // if either source or destination are SSL, we cannot use JDK 1.4
        // NIO selectors, but have to fall back on separate threads per connection

        if (key.ssl() || value.ssl()) {
            // if(2 == 2) {
            SocketAcceptor acceptor = new SocketAcceptor(key, value);
            executor.execute(acceptor);
            continue;
        }

        // 2. Create a ServerSocketChannel
        sock_channel = ServerSocketChannel.open();
        sock_channel.configureBlocking(false);
        sock_channel.socket().bind(key);

        // 3. Register the selector with all server sockets. 'Key' is attachment, so we get it again on
        //    select(). That way we can associate it with the mappings hashmap to find the corresponding
        //    value
        sock_channel.register(selector, SelectionKey.OP_ACCEPT, key);
    }

    // 4. Start main loop. won't return until CTRL-C'ed        
    loop(selector);
}

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

protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException {
    ServerSocketChannel _channel = ServerSocketChannel.open();
    _channel.configureBlocking(false);
    _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort()));
    return _channel;
}

From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java

public void listen() throws Exception {
    doListen = true;/*from ww  w  .  ja v  a2s . c  o  m*/
    // allocate an unbound server socket channel
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    // Get the associated ServerSocket to bind it with
    ServerSocket serverSocket = serverChannel.socket();
    // create a new Selector for use below
    Selector selector = Selector.open();
    // set the port the server channel will listen to
    serverSocket.bind(new InetSocketAddress(bind, port));
    // set non-blocking mode for the listening socket
    serverChannel.configureBlocking(false);
    // register the ServerSocketChannel with the Selector
    serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (doListen) {
        // this may block for a long time, upon return the
        // selected set contains keys of the ready channels
        try {

            //System.out.println("Selecting with timeout="+timeout);
            int n = selector.select(timeout);
            //System.out.println("select returned="+n);
            if (n == 0) {
                continue; // nothing to do
            }
            // get an iterator over the set of selected keys
            Iterator it = selector.selectedKeys().iterator();
            // look at each key in the selected set
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                // Is a new connection coming in?
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    registerChannel(selector, channel, SelectionKey.OP_READ,
                            new ObjectReader(channel, selector, callback));
                }
                // is there data to read on this channel?
                //System.out.println("key readable="+key.isReadable());
                if (key.isReadable()) {
                    readDataFromSocket(key);
                } else {
                    //System.out.println("This shouldn't get called");
                    key.interestOps(key.interestOps() & (~key.OP_WRITE));
                }

                // remove key from selected set, it's been handled
                it.remove();
            }
            //System.out.println("Done with loop");
        } catch (java.nio.channels.CancelledKeyException nx) {
            log.warn("Replication client disconnected, error when polling key. Ignoring client.");
        } catch (Exception x) {
            log.error("Unable to process request in ReplicationListener", x);
        }

    } //while
    serverChannel.close();
    selector.close();
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to//from   w  w w  . ja  va2s  . c om
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to " + receiveBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;/*w w  w  . j  a  v  a2  s  . co  m*/
    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);
}

From source file:org.apache.nifi.processors.standard.ListenTCPRecord.java

@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    this.port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();

    final int readTimeout = context.getProperty(READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int maxSocketBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B)
            .intValue();/*  w ww  .  ja  v a 2 s. c  o  m*/
    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER)
            .asControllerService(RecordReaderFactory.class);

    // if the Network Interface Property wasn't provided then a null InetAddress will indicate to bind to all interfaces
    final InetAddress nicAddress;
    final String nicAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions()
            .getValue();
    if (!StringUtils.isEmpty(nicAddressStr)) {
        NetworkInterface netIF = NetworkInterface.getByName(nicAddressStr);
        nicAddress = netIF.getInetAddresses().nextElement();
    } else {
        nicAddress = null;
    }

    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    // create a ServerSocketChannel in non-blocking mode and bind to the given address and port
    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(nicAddress, port));

    this.dispatcher = new SocketChannelRecordReaderDispatcher(serverSocketChannel, sslContext, clientAuth,
            readTimeout, maxSocketBufferSize, maxConnections, recordReaderFactory, socketReaders, getLogger());

    // start a thread to run the dispatcher
    final Thread readerThread = new Thread(dispatcher);
    readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]");
    readerThread.setDaemon(true);
    readerThread.start();
}

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

private int startFileTransferChannel(String dirName, FileChannel[] fileChannelList) {
    int port = -1;
    try {/*w ww  . ja v  a  2s  .c  o m*/
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ServerSocket serverSocket = ssc.socket();
        serverSocket.bind(null);
        port = serverSocket.getLocalPort();

        new FileTransferThread(dirName, ssc, fileChannelList).start();
        //LOG.info("File transfer thread is started and read method is done");
    } catch (IOException e) {
        LOG.warn("starting file transfer is fail", e);
    }

    return port;
}

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

private static void setListenerSocketOptions(ServerSocketChannel channel) throws IOException {
    channel.socket().setReuseAddress(true);
    channel.configureBlocking(false);
}