Example usage for java.nio.channels SelectionKey OP_READ

List of usage examples for java.nio.channels SelectionKey OP_READ

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey OP_READ.

Prototype

int OP_READ

To view the source code for java.nio.channels SelectionKey OP_READ.

Click Source Link

Document

Operation-set bit for read operations.

Usage

From source file:org.cloudata.core.commitlog.pipe.InitState.java

public boolean connectToNext(Pipe.Context ctx) throws IOException {
    if (ctx.nextChannel.finishConnect()) {
        ctx.deregisterFromSelect(ctx.nextChannel, SelectionKey.OP_CONNECT);
        ctx.registerToSelect(ctx.nextChannel, SelectionKey.OP_READ);
        writeToNext(ctx);//w  w  w  .ja  v a  2 s. c  o m
        return true;
    } else {
        ctx.registerToSelect(ctx.nextChannel, SelectionKey.OP_CONNECT);
        return false;
    }
}

From source file:org.limewire.mojito.io.MessageDispatcherImpl.java

@Override
public void bind(SocketAddress address) throws IOException {
    synchronized (lock) {
        if (isBound()) {
            throw new IOException("DatagramChannel is already bound");
        }//  www  . j  a v  a2s . c om

        channel = DatagramChannel.open();
        channel.configureBlocking(false);

        selector = Selector.open();
        channel.register(selector, SelectionKey.OP_READ);

        DatagramSocket socket = channel.socket();
        socket.setReuseAddress(false);
        socket.setReceiveBufferSize(RECEIVE_BUFFER_SIZE);
        socket.setSendBufferSize(SEND_BUFFER_SIZE);

        socket.bind(address);
    }
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void run() throws Exception {
    ByteBuffer recvBuffer = ByteBuffer.allocate(1100);

    while (true) {
        selector.select();//  w  w  w .  ja  v  a  2s . c om
        if (stopFlag) {
            return;
        }

        for (DatagramChannel channel : sendQueue.keySet()) {
            if (!sendQueue.get(channel).isEmpty()) {
                channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            } else {
                channel.register(selector, SelectionKey.OP_READ);
            }
        }

        for (SelectionKey key : selector.selectedKeys()) {
            if (!key.isValid()) {
                continue;
            }

            DatagramChannel channel = (DatagramChannel) key.channel();

            if (key.isReadable()) {
                recvBuffer.clear();
                InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer);
                recvBuffer.flip();
                for (UdpCommunicatorListener listener : listeners) {
                    try {
                        listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            } else if (key.isWritable()) {
                LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue
                        .get(channel);
                ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll();

                if (next != null) {
                    try {
                        channel.send(next.getValue(), next.getKey());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            }
        }
    }
}

From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java

protected void invokeExceptionHandler(SelectionKey selectionKey, Consumer<Exception> exceptionHandler,
        Exception exception) {// ww w  .  j a  va 2 s  .  co m
    selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
    try {
        exceptionHandler.accept(exception);
    } catch (Exception e) {
        LOG.error("Read exception handler failed", e);
    }
}

From source file:net.sf.cindy.impl.ChannelSession.java

private void onEnableRead() {
    if (readKey != null && readKey.isValid()) {
        readKey.interestOps(readKey.interestOps() | SelectionKey.OP_READ);
    }
}

From source file:net.jenet.Host.java

/**
 * Creates a new <code>Host</code> object. If the incoming/outgoing
 * bandwidths are not bounded, the host will drop unreliable packets in
 * order to keep them below the fixed limits. This parameter also influences
 * the number and size of the reliable packets that may be handled at once.
 * //from  w  ww  .j a  va2 s. co m
 * @param address
 *            The to bind this host to (<emph>ie</emph> the address at
 *            which other peers may connect to this one) or
 *            <code>0</code> to get a system-assigned address.
 * @param maxConnections
 *            The maximum number of peers/connections that this host will be
 *            able to connect to.
 * @param incomingBandwith
 *            The maximum incoming bandwidth in bytes/second (0 =
 *            unbounded).
 * @param outgoingBandwith
 *            The maximum outgoing bandwidth in bytes/second (0 =
 *            unbounded).
 * @throws IOException
 *             if it can not bind the port.
 * @throws ConfigurationException
 *             if the file enet.properties is not in the path
 */
public Host(InetSocketAddress address, int maxConnections, int incomingBandwith, int outgoingBandwith)
        throws IOException, ConfigurationException {
    super();
    communicationChannel = DatagramChannel.open();
    communicationChannel.configureBlocking(false);
    communicationChannel.socket().bind(address);
    communicationSelector = Selector.open();
    communicationChannel.register(communicationSelector, SelectionKey.OP_READ);
    LOG.debug("Host bound to address: " + address);
    this.address = (InetSocketAddress) communicationChannel.socket().getLocalSocketAddress();
    initHost(maxConnections, incomingBandwith, outgoingBandwith);
}

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

@Override
public void run() {
    try {/*from w  w  w .j a  va  2  s. c  o  m*/
        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:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java

@Override
public boolean notifyRead(SocketChannel channel) {
    logger.debug("notifyRead");
    if (state.get() == NetworkStateEnum.NETWORK_STATE_CONNECTED.value) {
        // //from w ww .j  a  va2s.  c  o  m
        opsChangeRequest.addOps(SelectionKey.OP_READ);
        // ?selector
        weakup();
        return true;
    }

    return false;
}

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

public void processConnect(SelectionKey sk) throws IOException {
    if (connected)
        return;//from w  ww .j ava2  s. co  m
    //?SocketChannel
    socketChannel.finishConnect();
    while (!socketChannel.isConnected()) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            // ??
        }
        socketChannel.finishConnect();
    }
    sk.interestOps(SelectionKey.OP_READ);
    connected = true;
    log.debug("??");
}

From source file:org.reunionemu.jreunion.server.Network.java

private void processAccept(SocketChannel socketChannel) throws IOException {

    socketChannel.configureBlocking(false);

    fireEvent(NetworkAcceptEvent.class, socketChannel);

    // Register it with the selector, for reading
    selector.wakeup();/* w w w  .j a v a2s. c  o m*/
    socketChannel.register(selector, SelectionKey.OP_READ);

}