Example usage for java.nio.channels Selector open

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

Introduction

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

Prototype

public static Selector open() throws IOException 

Source Link

Document

Opens a selector.

Usage

From source file:xyz.hexene.localvpn.LocalVPNService.java

@Override
public void onCreate() {
    super.onCreate();
    isRunning = true;/*from w  w  w.ja v a 2  s  .c  o  m*/
    setupVPN();
    try {
        udpSelector = Selector.open();
        tcpSelector = Selector.open();
        deviceToNetworkUDPQueue = new ConcurrentLinkedQueue<>();
        deviceToNetworkTCPQueue = new ConcurrentLinkedQueue<>();
        networkToDeviceQueue = new ConcurrentLinkedQueue<>();

        executorService = Executors.newFixedThreadPool(5);
        executorService.submit(new UDPInput(networkToDeviceQueue, udpSelector));
        executorService.submit(new UDPOutput(deviceToNetworkUDPQueue, udpSelector, this));
        executorService.submit(new TCPInput(networkToDeviceQueue, tcpSelector));
        executorService.submit(new TCPOutput(deviceToNetworkTCPQueue, networkToDeviceQueue, tcpSelector, this));
        executorService.submit(new VPNRunnable(vpnInterface.getFileDescriptor(), deviceToNetworkUDPQueue,
                deviceToNetworkTCPQueue, networkToDeviceQueue));
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent(BROADCAST_VPN_STATE).putExtra("running", true));
        Log.i(TAG, "Started");
    } catch (IOException e) {
        // TODO: Here and elsewhere, we should explicitly notify the user of any errors
        // and suggest that they stop the service, since we can't do it ourselves
        Log.e(TAG, "Error starting service", e);
        cleanup();
    }
}

From source file:hosts.file.localvpn.LocalVPNService.java

@Override
public void onCreate() {
    super.onCreate();
    localVPNService = this;
    isRunning = true;//www.  jav a2  s. c  o m
    setupVPN();
    try {
        udpSelector = Selector.open();
        tcpSelector = Selector.open();
        deviceToNetworkUDPQueue = new ConcurrentLinkedQueue<>();
        deviceToNetworkTCPQueue = new ConcurrentLinkedQueue<>();
        networkToDeviceQueue = new ConcurrentLinkedQueue<>();

        executorService = Executors.newFixedThreadPool(5);
        executorService.submit(new UDPInput(networkToDeviceQueue, udpSelector));
        executorService.submit(new UDPOutput(deviceToNetworkUDPQueue, udpSelector, this));
        executorService.submit(new TCPInput(networkToDeviceQueue, tcpSelector));
        executorService.submit(new TCPOutput(deviceToNetworkTCPQueue, networkToDeviceQueue, tcpSelector, this));
        executorService.submit(new VPNRunnable(vpnInterface.getFileDescriptor(), deviceToNetworkUDPQueue,
                deviceToNetworkTCPQueue, networkToDeviceQueue));
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent(BROADCAST_VPN_STATE).putExtra("running", true));
        Log.i(TAG, "Started");
    } catch (IOException e) {
        // TODO: Here and elsewhere, we should explicitly notify the user of any errors
        // and suggest that they stop the service, since we can't do it ourselves
        Log.e(TAG, "Error starting service", e);
        cleanup();
    }
}

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

public SelectorThread() throws IOException {
    this.selector = Selector.open();
    this.thread = new Thread(this);
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

SocketInfo select() throws IOException {
    log.trace("select()");

    Selector selector = Selector.open();

    SocketInfo selectedSocket = initConnections(selector);
    if (selectedSocket != null) {
        return selectedSocket;
    }/*from  w w w  .  j  a  v  a 2s  .  co  m*/

    URI selectedAddress = null;
    SocketChannel channel = null;
    try {
        SelectionKey key = selectFirstConnectedSocketChannel(selector);
        if (key == null) {
            return null;
        }

        channel = (SocketChannel) key.channel();
        selectedAddress = (URI) key.attachment();
    } finally {
        try {
            closeSelector(selector, channel);
        } catch (Exception e) {
            log.error("Error while closing selector", e);
        }
    }

    if (channel != null) {
        channel.configureBlocking(true);
        return new SocketInfo(selectedAddress, channel.socket());
    }

    return null;
}

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

/**
 * Porter./*from w  ww .j  a  v a  2 s .  c om*/
 */
public Porter() {
    ports = new ArrayList<IPort>();
    proxies = new ArrayList<IProxy>();
    newConnections = new Vector<Object>();
    disposeQueue = new LinkedList<Object>();
    setName("Porter");
    setDaemon(true);
    // Selector
    try {
        selector = Selector.open();
    } catch (IOException e) {
        log.debug(e);
        throw new RuntimeException(e);
    }
}

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

public SelectorThread(final String threadName) throws IOException {
    this.selector = Selector.open();
    this.thread = new Thread(this, threadName);
}

From source file:org.sonews.daemon.sync.SynchronousNNTPDaemon.java

@Override
public void run() {
    try {// www. java  2s .  c  om
        Log.get().log(Level.INFO, "Server listening on port {0}", port);

        // Create a Selector that handles the SocketChannel multiplexing
        final Selector readSelector = Selector.open();
        final Selector writeSelector = Selector.open();

        // Start working threads
        final int workerThreads = Math.max(4, 2 * Runtime.getRuntime().availableProcessors());
        ConnectionWorker[] cworkers = new ConnectionWorker[workerThreads];
        for (int n = 0; n < workerThreads; n++) {
            cworkers[n] = new ConnectionWorker();
            cworkers[n].start();
        }
        Log.get().log(Level.INFO, "{0} worker threads started.", workerThreads);

        ChannelWriter.getInstance().setSelector(writeSelector);
        ChannelReader.getInstance().setSelector(readSelector);
        ChannelWriter.getInstance().start();
        ChannelReader.getInstance().start();

        final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(true); // Set to blocking mode

        // Configure ServerSocket; bind to socket...
        serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(this.port));

        while (isRunning()) {
            SocketChannel socketChannel;

            try {
                // As we set the server socket channel to blocking mode the
                // accept()
                // method will block.
                socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                assert socketChannel.isConnected();
                assert socketChannel.finishConnect();
            } catch (IOException ex) {
                // Under heavy load an IOException "Too many open files may
                // be thrown. It most cases we should slow down the
                // connection accepting, to give the worker threads some
                // time to process work.
                Log.get().log(Level.SEVERE, "IOException while accepting connection: {0}", ex.getMessage());
                Log.get().info("Connection accepting sleeping for seconds...");
                Thread.sleep(5000); // 5 seconds
                continue;
            }

            //FIXME conn should be NNTPConnection
            final SynchronousNNTPConnection conn = (SynchronousNNTPConnection) context
                    .getBean("syncNNTPConnection", NNTPConnection.class);
            conn.setChannelWrapper(new SocketChannelWrapperFactory(socketChannel).create());
            Connections.getInstance().add(conn);

            try {
                SelectionKey selKeyWrite = registerSelector(writeSelector, socketChannel,
                        SelectionKey.OP_WRITE);
                registerSelector(readSelector, socketChannel, SelectionKey.OP_READ);

                Log.get().log(Level.INFO, "Connected: {0}", socketChannel.socket().getRemoteSocketAddress());

                // Set write selection key and send hello to client
                conn.setWriteSelectionKey(selKeyWrite);
                conn.println("200 " + Config.inst().get(Config.HOSTNAME, "localhost") + " <unknown version>" // + Application.VERSION
                        + " news server ready - (posting ok).");
            } catch (CancelledKeyException cke) {
                Log.get().log(Level.WARNING, "CancelledKeyException {0} was thrown: {1}",
                        new Object[] { cke.getMessage(), socketChannel.socket() });
            } catch (ClosedChannelException cce) {
                Log.get().log(Level.WARNING, "ClosedChannelException {0} was thrown: {1}",
                        new Object[] { cce.getMessage(), socketChannel.socket() });
            }
        }
    } catch (BindException ex) {
        // Could not bind to socket; this is a fatal, so perform a shutdown
        Log.get().log(Level.SEVERE, ex.getLocalizedMessage() + " -> shutdown sonews", ex);
        setRunning(false);
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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

public void start() throws GridException {
    if (_listener == null) {
        throw new IllegalStateException("GridTransportListener is not set");
    }/*from w w w .java  2 s.  c  om*/

    final Selector connectSelector;
    try {
        connectSelector = Selector.open();
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe);
        throw new GridException("Failed to open Selectors", ioe);
    }
    final int port = config.getTransportServerPort();
    try {
        startListening(connectSelector, port);
    } catch (IOException e) {
        final String errmsg = "Failed to create selector on port: " + port;
        LOG.error(errmsg, e);
        throw new GridException(errmsg, e);
    }

    final int nthreads = config.getMessageProcessorPoolSize();
    final ExecutorService exec = ExecutorFactory.newFixedThreadPool(nthreads, "NioMessageProcessor", false);

    final int nSelectors = config.getSelectorReadThreadsCount();
    final SelectorReadThread[] readThreads = new SelectorReadThread[nSelectors];
    this._readThreads = readThreads;
    final AcceptorThread acceptorThread = new AcceptorThread(connectSelector, readThreads);
    this._acceptorThread = acceptorThread;

    for (int i = 0; i < nSelectors; i++) {
        final SelectorReadThread th;
        try {
            th = new SelectorReadThread(exec, _listener);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new GridException("Failed to instantiate a SelectorReadThread instance", e);
        }
        th.setName("GridNioServer-SelectorReadThread#" + i);
        th.start();
        readThreads[i] = th;
    }
    acceptorThread.start();
}

From source file:idgs.client.TcpClient.java

private void initialize() throws IOException {
    servAddr = new InetSocketAddress(host, port);
    // create selector
    try {/* ww w  .j a  va2 s .c  om*/
        selector = Selector.open();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

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

/** Constructor - creates a new NIO Selector */
public NIOSocketSelector(EventLoop eventLoop) throws IOException {

    _eventLoop = eventLoop;//  w  ww  .ja v  a  2s  . co  m
    _selector = Selector.open();
}