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:com.tera.common.network.nio.MMOConnection.java

final void disableReadInterest() {
    try {/*www  .  j a va 2 s  . c o m*/
        getSelectionKey().interestOps(getSelectionKey().interestOps() & ~SelectionKey.OP_READ);
    } catch (CancelledKeyException e) {
        // ignore
    }
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

@Override
protected void handle(SelectionKey key) {
    System.out.println("ReadWriteThread.handle() " + describeInterestOps(key.interestOps()) + ", ready: "
            + describeInterestOps(key.readyOps()));
    switch (key.readyOps()) {
    case SelectionKey.OP_CONNECT:
        finishConnection(key);// w  w  w. j  av  a  2  s  .  c o m
        break;
    case SelectionKey.OP_READ:
        readPacket(key);
        break;
    case SelectionKey.OP_WRITE:
        writePacket(key);
        break;
    case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
        writePacket(key);
        // key might have been invalidated on writePacket
        if (key.isValid())
            readPacket(key);
        break;
    default:
        System.err.println("Unknown readyOps: " + key.readyOps() + " for " + key.attachment());
        break;
    }
}

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

/**
 * Called to initiate a unit of work by this worker thread
 * on the provided SelectionKey object.  This method is
 * synchronized, as is the run() method, so only one key
 * can be serviced at a given time.//from  w  w w  . j  a v  a2s.  c om
 * Before waking the worker thread, and before returning
 * to the main selection loop, this key's interest set is
 * updated to remove OP_READ.  This will cause the selector
 * to ignore read-readiness for this channel while the
 * worker thread is servicing it.
 */
synchronized void serviceChannel(SelectionKey key, boolean synchronous) {
    this.key = key;
    this.synchronous = synchronous;
    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
    this.notify(); // awaken the thread
}

From source file:com.springrts.springls.Clients.java

/**
 * Will create new <code>Client</code> object, add it to the 'clients' list
 * and register its socket channel with 'readSelector'.
 * @param sendBufferSize specifies the sockets send buffer size.
 *///from ww w  .j  av a 2  s. co m
public Client addNewClient(SocketChannel chan, Selector readSelector, int sendBufferSize) {
    Client client = new Client(chan);
    client.receiveContext(context);
    clients.add(client);

    // register the channel with the selector
    // store a new Client as the Key's attachment
    try {
        chan.configureBlocking(false);
        chan.socket().setSendBufferSize(sendBufferSize);
        // TODO this doesn't seem to have an effect with java.nio
        //chan.socket().setSoTimeout(TIMEOUT_LENGTH);
        client.setSelKey(chan.register(readSelector, SelectionKey.OP_READ, client));
    } catch (IOException ioex) {
        LOG.warn("Failed to establish a connection with a client", ioex);
        killClient(client, "Failed to establish a connection");
        return null;
    }

    return client;
}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

@Override
public boolean notifyRead(SocketChannel channel) {
    logger.debug("notifyRead");
    if (channel == null) {
        return false;
    }/*from   w  w w .j ava  2  s .c om*/
    SocketChannelOPSChangeRequest request = opsChangeRequstMap.get(channel);
    if (request == null) {
        // Socket
        return false;
    }
    // 
    request.addOps(SelectionKey.OP_READ);
    // ?selector
    weakup();

    return true;
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

private void doAccept(SelectionKey key) {

    SocketChannel clientSocket = null;

    try {//from w  w w .  ja  v  a  2  s . c o m
        clientSocket = this.listeningSocket.accept();
        if (clientSocket == null) {
            LOG.error("Client socket is null");
            return;
        }
    } catch (IOException ioe) {
        LOG.error(ioe);
        return;
    }

    final IncomingConnection incomingConnection = new IncomingConnection(this.byteBufferedChannelManager,
            clientSocket);
    SelectionKey clientKey = null;
    try {
        clientSocket.configureBlocking(false);
        clientKey = clientSocket.register(this.selector, SelectionKey.OP_READ);
        clientKey.attach(incomingConnection);
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(clientKey, ioe);
    }
}

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

public void listen() throws Exception {
    doListen = true;//w  ww  .j a v a  2s  .  co  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:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Attempts to accept incoming new connections.
 * //from   w ww  .  j  a v  a  2 s . c om
 * @return
 *       True if there was no error, false if an error occured.
 */
private boolean acceptConnections() {
    SocketChannel socketChannel = null;

    // Only bother if the connection is open.
    if (serverSocketChannel.isOpen()) {

        // Attempt to get a connection.
        try {
            socketChannel = serverSocketChannel.accept();
        } catch (Exception e) {
            log.error("Unexpected IO exception when accepting a connection.", e);
            return false;
        }

        // If there was a client connecting, take care of them.
        // Make sure to attach a new ClientInfo that we will fill out later upon validation.
        if (socketChannel != null) {
            try {
                log.info("Incoming new client connection from {}.",
                        socketChannel.getRemoteAddress().toString());
                ClientInfo clientInfo = new ClientInfo(socketChannel.getRemoteAddress().toString());
                socketChannel.configureBlocking(false);
                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.register(selector, SelectionKey.OP_READ, clientInfo);
                clientInfo.markMessageReceived(); // Prevent timing out from a connection.

                //               // TEST
                //               int amount = 1024 * 16;
                //               byte[] hi = new byte[amount];
                //               for (int i = 0; i < amount; i++)
                //                  hi[i] = (byte)(Math.random() * 255);
                //               ByteBuffer bb = ByteBuffer.allocate(amount);
                //               bb.put(hi);
                //               bb.flip();
                //               
                //               int wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("Server wrote: " + wrote + " bytes to a client");
                //               }
                //               
                //               Thread.sleep(4000);
                //               
                //               bb = ByteBuffer.allocate(5);
                //               bb.put(new byte[] { 1, 2, 3, 4, 5 });
                //               bb.flip();
                //               wrote = 0;
                //               while (bb.hasRemaining()) {
                //                  wrote = socketChannel.write(bb);
                //                  System.out.println("2) Server wrote: " + wrote + " bytes to a client");
                //               }

                // TODO - send global version of the file.
            } catch (ClosedChannelException e) {
                log.error("Channel closed exception when registering a connected client.", e);
                return false;
            } catch (IOException e) {
                log.error("IO exception when registering a new client connection.", e);
                return false;
            } catch (Exception e) {
                log.error("Unexpected exception when registering a new client connection.", e);
                return false;
            }
        }
    }

    // Signal all is good.
    return true;
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;//from w  w  w.ja  va 2 s . c o m
    SocketChannel channel;
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {

            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {

                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {

                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {

                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {

                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {

                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {

                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {

                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}

From source file:org.gldapdaemon.core.ldap.LDAPListener.java

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;//from w  ww .  ja  v a 2  s . c om
    SocketChannel channel;
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {
            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {
                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                sleep(5000);
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {
                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {
                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    sleep(5000);
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        sleep(5000);
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {
                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {
                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {
                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {
                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}