Java Code Examples for java.nio.channels.SelectionKey#isWritable()

The following examples show how to use java.nio.channels.SelectionKey#isWritable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PassiveRedisIndexer.java    From mldht with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isValid() && key.isConnectable()) {
		chan.finishConnect();
		conMan.interestOpsChanged(this);
	}
		
	if(key.isValid() && key.isReadable())
		read();
	if(key.isValid() && key.isWritable()) {
		awaitingWriteNotification = false;
		tryWrite.run();
		conMan.interestOpsChanged(this);
	}
		
	
}
 
Example 2
Source File: SqueakSocket.java    From trufflesqueak with MIT License 6 votes vote down vote up
@TruffleBoundary
protected final long sendData(final byte[] data, final int start, final int count) throws IOException {
    final ByteBuffer buffer = ByteBuffer.wrap(data, start, count);
    selector.selectNow();
    final Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
    while (keys.hasNext()) {
        final SelectionKey key = keys.next();
        if (key.isWritable()) {
            final long written = sendDataTo(buffer, key);
            LogUtils.SOCKET.finer(() -> this + " written: " + written);
            keys.remove();
            return written;
        }
    }

    throw new IOException("No writable key found");
}
 
Example 3
Source File: TThreadedSelectorServer.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately: If there are existing
 * connections with data waiting to be read, read it, buffering until a
 * whole frame has been read. If there are any pending responses, buffer
 * them until their target client is available, and then send the data.
 */
private void select() {
  try {
    // wait for io events.
    selector.select();

    // process the io events we received
    Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
    while (!stopped_ && selectedKeys.hasNext()) {
      SelectionKey key = selectedKeys.next();
      selectedKeys.remove();

      // skip if not valid
      if (!key.isValid()) {
        cleanupSelectionKey(key);
        continue;
      }

      if (key.isReadable()) {
        // deal with reads
        handleRead(key);
      } else if (key.isWritable()) {
        // deal with writes
        handleWrite(key);
      } else {
        LOGGER.warn("Unexpected state in select! " + key.interestOps());
      }
    }
  } catch (IOException e) {
    LOGGER.warn("Got an IOException while selecting!", e);
  }
}
 
Example 4
Source File: Firehose.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isValid() && key.isReadable())
		read();
	if(key.isValid() && key.isWritable())
		write();
}
 
Example 5
Source File: ActiveLookupProvider.java    From bt with Apache License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isValid() && key.isWritable())
		write();
	if(key.isValid() && key.isReadable())
		read();
}
 
Example 6
Source File: TThreadedSelectorServer.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately: If there are existing
 * connections with data waiting to be read, read it, buffering until a
 * whole frame has been read. If there are any pending responses, buffer
 * them until their target client is available, and then send the data.
 */
private void select() {
  try {
    // wait for io events.
    selector.select();

    // process the io events we received
    Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
    while (!stopped_ && selectedKeys.hasNext()) {
      SelectionKey key = selectedKeys.next();
      selectedKeys.remove();

      // skip if not valid
      if (!key.isValid()) {
        cleanupSelectionKey(key);
        continue;
      }

      if (key.isReadable()) {
        // deal with reads
        handleRead(key);
      } else if (key.isWritable()) {
        // deal with writes
        handleWrite(key);
      } else {
        LOGGER.warn("Unexpected state in select! " + key.interestOps());
      }
    }
  } catch (IOException e) {
    LOGGER.warn("Got an IOException while selecting!", e);
  }
}
 
Example 7
Source File: NIOLooper.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
private void handleSelectedKeys() {
  Set<SelectionKey> selectedKeys = selector.selectedKeys();
  Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
  while (keyIterator.hasNext()) {
    SelectionKey key = keyIterator.next();
    keyIterator.remove();

    ISelectHandler callback = (ISelectHandler) key.attachment();

    if (!key.isValid()) {
      // This method key.channel() will continue to return the channel even after the
      // key is cancelled.
      callback.handleError(key.channel());
      continue;
    }

    // We need to check whether the key is still valid since:
    // 1. The key could be cancelled by last operation
    // 2. The process might not fail-fast or throw exceptions after the key is cancelled
    if (key.isValid() && key.isWritable()) {
      callback.handleWrite(key.channel());
    }

    if (key.isValid() && key.isReadable()) {
      callback.handleRead(key.channel());
    }

    if (key.isValid() && key.isConnectable()) {
      callback.handleConnect(key.channel());
    }

    if (key.isValid() && key.isAcceptable()) {
      callback.handleAccept(key.channel());
    }

  }
}
 
Example 8
Source File: RPCServer.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	// schedule async writes first before spending thread time on reads
	if(key.isValid() && key.isWritable()) {
		writeState.set(WRITE_STATE_IDLE);
		connectionManager.interestOpsChanged(this);
		dh_table.getScheduler().execute(this::writeEvent);
	}
	if(key.isValid() && key.isReadable())
		readEvent();
		
}
 
Example 9
Source File: TestMessageIO.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static boolean awaitOp(Selector selector, SelectionKey key, int op) throws IOException {
    long end = System.currentTimeMillis() + SELECTION_TIMEOUT_MS;
    boolean selected = false;
    while (!selected) {
        // Check timeout
        long remaining = end - System.currentTimeMillis();
        if (remaining < 0) {
            break;
        }

        // Select up to remaining millis
        selector.select(remaining);

        // Handle op if possible
        switch (op) {
        case SelectionKey.OP_READ:
            selected |= key.isReadable();
            break;
        case SelectionKey.OP_ACCEPT:
            selected |= key.isAcceptable();
            break;
        case SelectionKey.OP_WRITE:
            selected |= key.isWritable();
            break;
        case SelectionKey.OP_CONNECT:
            selected |= key.isConnectable();
            break;
        }
    }
    return selected;
}
 
Example 10
Source File: MqttChannelTestBase.java    From xenqtt with Apache License 2.0 5 votes vote down vote up
/**
 * reads and writes until the specified number of client and broker messages are received
 * 
 * @param clientMessageCount
 *            Number of client messages to read
 * @param brokerMessageCount
 *            Number of broker messages to read
 * @param timeoutMillis
 *            Millis to wait for the client and broker message count to be reached
 */
boolean readWrite(int clientMessageCount, int brokerMessageCount, long timeoutMillis) throws Exception {

	long end = timeoutMillis == 0 ? 0 : System.currentTimeMillis() + timeoutMillis;

	clientHandler.clearMessages();
	brokerHandler.clearMessages();

	while (brokerHandler.messageCount() < brokerMessageCount || clientHandler.messageCount() < clientMessageCount) {

		if (end != 0) {
			long time = end - System.currentTimeMillis();
			if (time > 0) {
				selector.select(time);
			}
		} else {
			selector.select();
		}

		Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
		if (!iter.hasNext() && System.currentTimeMillis() >= end) {
			return false;
		}
		while (iter.hasNext()) {
			SelectionKey key = iter.next();
			MqttChannel channel = (MqttChannel) key.attachment();
			if (key.isValid() && key.isReadable()) {
				channel.read(now + 10);
			}
			if (key.isValid() && key.isWritable()) {
				channel.write(now);
			}
			iter.remove();
		}
	}

	return true;
}
 
Example 11
Source File: NioDatagramAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected boolean isWritable(DatagramChannel handle) {
    SelectionKey key = handle.keyFor(selector);

    if ((key == null) || (!key.isValid())) {
        return false;
    }

    return key.isWritable();
}
 
Example 12
Source File: EchoServer.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void startServer() throws Exception {
    selector = SelectorProvider.provider().openSelector();

    // Create non-blocking server socket.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    // Bind the server socket to localhost.
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), 8888);
    ssc.socket().bind(isa);

    // Register the socket for select events.
    SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);

    // Loop forever.
    for (;;) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator i = readyKeys.iterator();

        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            i.remove();

            if (sk.isAcceptable()) {
                doAccept(sk);
            }
            if (sk.isValid() && sk.isReadable()) {
                doRead(sk);
            }
            if (sk.isValid() && sk.isWritable()) {
                doWrite(sk);
            }
        }
    }
}
 
Example 13
Source File: SocketFramework.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void process( SelectionKey key ) throws IOException {
    if (key.isReadable()) {
        readData(key);
    }
    if (key.isValid() && key.isWritable()) {
        writeData(key);
    }        
}
 
Example 14
Source File: NioSender.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * State machine to send data
 * @param key SelectionKey
 * @return boolean
 * @throws IOException
 */
public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
    int ops = key.readyOps();
    key.interestOps(key.interestOps() & ~ops);
    //in case disconnect has been called
    if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key.");
    if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled.");
    if ( key.isConnectable() ) {
        if ( socketChannel.finishConnect() ) {
            completeConnect();
            if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return false;
        } else  {
            //wait for the connection to finish
            key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
            return false;
        }//end if
    } else if ( key.isWritable() ) {
        boolean writecomplete = write(key);
        if ( writecomplete ) {
            //we are completed, should we read an ack?
            if ( waitForAck ) {
                //register to read the ack
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            } else {
                //if not, we are ready, setMessage will reregister us for another write interest
                //do a health check, we have no way of verify a disconnected
                //socket since we don't register for OP_READ on waitForAck=false
                read(key);//this causes overhead
                setRequestCount(getRequestCount()+1);
                return true;
            }
        } else {
            //we are not complete, lets write some more
            key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
        }//end if
    } else if ( key.isReadable() ) {
        boolean readcomplete = read(key);
        if ( readcomplete ) {
            setRequestCount(getRequestCount()+1);
            return true;
        } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        }//end if
    } else {
        //unknown state, should never happen
        log.warn("Data is in unknown state. readyOps="+ops);
        throw new IOException("Data is in unknown state. readyOps="+ops);
    }//end if
    return false;
}
 
Example 15
Source File: AbstractDebugServer.java    From unidbg with Apache License 2.0 4 votes vote down vote up
private void runServer() {
    selector = null;
    serverSocketChannel = null;
    socketChannel = null;
    try {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.socket().bind(new InetSocketAddress(DEFAULT_PORT));

        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    } catch(IOException ex) {
        throw new IllegalStateException(ex);
    }

    serverShutdown = false;
    serverRunning = true;

    System.err.println("Start " + this + " server on port: " + DEFAULT_PORT);
    onServerStart();

    while(serverRunning) {
        try {
            int count = selector.select(50);
            if (count <= 0) {
                if (!isDebuggerConnected() && System.in.available() > 0) {
                    String line = new Scanner(System.in).nextLine();
                    if ("c".equals(line)) {
                        serverRunning = false;
                        break;
                    } else {
                        System.out.println("c: continue");
                    }
                }
                continue;
            }

            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = selectedKeys.next();
                if (key.isValid()) {
                    if (key.isAcceptable()) {
                        onSelectAccept(key);
                    }
                    if (key.isReadable()) {
                        onSelectRead(key);
                    }
                    if (key.isWritable()) {
                        onSelectWrite(key);
                    }
                }
                selectedKeys.remove();
            }

            processInput(input);
        } catch(Throwable e) {
            if (log.isDebugEnabled()) {
                log.debug("run server ex", e);
            }
        }
    }

    IOUtils.closeQuietly(serverSocketChannel);
    serverSocketChannel = null;
    IOUtils.closeQuietly(selector);
    selector = null;
    closeSocketChannel();
    resumeRun();
}
 
Example 16
Source File: Transfer.java    From nitroshare-android with MIT License 4 votes vote down vote up
/**
 * Perform the transfer until it completes or an error occurs
 */
@Override
public void run() {
    try {
        // Indicate which operations select() should select for
        SelectionKey selectionKey = mSocketChannel.register(
                mSelector,
                mTransferStatus.getDirection() == TransferStatus.Direction.Receive ?
                        SelectionKey.OP_READ :
                        SelectionKey.OP_CONNECT
        );

        // For a sending transfer, connect to the remote device
        if (mTransferStatus.getDirection() == TransferStatus.Direction.Send) {
            mSocketChannel.connect(new InetSocketAddress(mDevice.getHost(), mDevice.getPort()));
        }

        while (true) {
            mSelector.select();
            if (mStop) {
                break;
            }
            if (selectionKey.isConnectable()) {
                mSocketChannel.finishConnect();
                selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);

                synchronized (mTransferStatus) {
                    mTransferStatus.setState(TransferStatus.State.Transferring);
                    notifyStatusChangedListeners();
                }
            }
            if (selectionKey.isReadable()) {
                if (!processNextPacket()) {
                    if (mTransferStatus.getDirection() == TransferStatus.Direction.Receive) {
                        selectionKey.interestOps(SelectionKey.OP_WRITE);
                    } else {
                        break;
                    }
                }
            }
            if (selectionKey.isWritable()) {
                if (!sendNextPacket()) {
                    if (mTransferStatus.getDirection() == TransferStatus.Direction.Receive) {
                        break;
                    } else {
                        selectionKey.interestOps(SelectionKey.OP_READ);
                    }
                }
            }
        }

        // Close the socket
        mSocketChannel.close();

        // If interrupted, throw an error
        if (mStop) {
            throw new IOException("transfer was cancelled");
        }

        // Indicate success
        synchronized (mTransferStatus) {
            mTransferStatus.setState(TransferStatus.State.Succeeded);
            notifyStatusChangedListeners();
        }

    } catch (IOException e) {
        synchronized (mTransferStatus) {
            mTransferStatus.setState(TransferStatus.State.Failed);
            mTransferStatus.setError(e.getMessage());
            notifyStatusChangedListeners();
        }
    }
}
 
Example 17
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 4 votes vote down vote up
private void startServer() throws Exception{
        //声明一个selector
        selector= SelectorProvider.provider().openSelector();

        //声明一个server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //声明服务器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服务器端的socket channel绑定在这个端口。
        ssc.socket().bind(isa);
        //把一个socketchannel注册到一个selector上,同时选择监听的事件,SelectionKey.OP_ACCEPT表示对selector如果
        //监听到注册在它上面的server socket channel准备去接受一个连接,或 有个错误挂起,selector将把OP_ACCEPT加到
        //key ready set 并把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
 
Example 18
Source File: PubSubClient.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** The main client loop when we've connected to the server. Selects on the selector and does async read/write */
private void ClientThreadMainLoop(SocketChannel channel) throws IOException {
    // Create subscription message if we have some already
    TopicMessage subscriptions = null;
    synchronized (this) {
        if (subscribers.size() > 0) {
            log.debug("Sending existing subscriptions");
            ControlMessage.Builder msg = ControlMessage.newBuilder();
            for (ByteString topic : subscribers.keySet()) {
                msg.addTopicSubscribe(topic);
            }
            subscriptions = new ProtobufMessage(CONTROL_TOPIC, msg.build());
        }
    }

    // Create a message reader and writer
    log.debug("Creating client reader and writer for channel {}", channel);
    ClientReader reader = new ClientReader(channel);
    ClientWriter writer = new ClientWriter(channel, subscriptions);
    SelectionKey k = channel.register(selector, SelectionKey.OP_READ);

    // Do main loop
    while (!Thread.currentThread().isInterrupted()) {
        // Register for read and write as needed
        int ops = SelectionKey.OP_READ;
        if (writer.canWrite()) {
            ops |= SelectionKey.OP_WRITE;
        }
        k.interestOps(ops);

        // Wait until we can do something
        selector.select(1000);

        // Deal with keys
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            // Get next key, remove from selected
            SelectionKey selected = it.next();
            it.remove();

            // Cancel if necessary
            if (!selected.isValid()) {
                selected.cancel();
            }

            // Do nothing if its not our key... why this can happen, I do
            // not know
            if (selected != k) {
                continue;
            }

            // Check to see whether we can read and write
            if (k.isWritable()) {
                log.debug("Writing");
                boolean hasRemaining = writer.write();
                
                // Signal anybody waiting
                if (!hasRemaining) {
                    notifyLock.lock();
                    try {
                        notifyCondition.signalAll();
                    } finally {
                        notifyLock.unlock();
                    }
                }
            } else if (k.isReadable()) {
                log.debug("Reading");
                if (!reader.read()) {
                    log.debug("Reader reached end of stream");
                    k.cancel();
                    return;
                }
            }
        }
    }
}
 
Example 19
Source File: RunLoop.java    From whiskey with Apache License 2.0 4 votes vote down vote up
void run(final boolean blocking) {

        loops++;
        signal.set(false);

        // Check standard tasks
        Runnable currentTask;
        while ((currentTask = tasks.poll()) != null) {
            executions++;
            currentTask.run();
        }

        long selectTimeout = 0;

        // Check scheduled tasks and setup maximum delay
        ScheduledRunnable nextScheduledTask;
        while (!scheduledTasks.isEmpty()) {
            nextScheduledTask = scheduledTasks.peek();
            long now = clock.now();
            if (nextScheduledTask.tolerance > 0 &&
                nextScheduledTask.triggerPoint <= now - nextScheduledTask.tolerance) {
                // Discard the task - we missed the tolerance window
                scheduledTasks.poll();
            } else if (nextScheduledTask.triggerPoint <= now) {
                // It's time to run the task
                executions++;
                nextScheduledTask.run();
                scheduledTasks.poll();
            } else {
                // Determine the select timeout and break
                selectTimeout = nextScheduledTask.triggerPoint - now;
                break;
            }
        }

        int readyChannels = 0;

        // Select
        try {
            selecting = true;
            if (blocking && tasks.isEmpty() && !signal.get()) {
                readyChannels = selector.select(selectTimeout);
            } else {
                readyChannels = selector.selectNow();
            }
            selecting = false;
        } catch (IOException e) {
            // Recovery would have to involve re-registering all sockets
            // on a new Selector. Consider this fatal for now.
            throw new RuntimeException(e);
        }

        if (readyChannels > 0) {
            Set<SelectionKey> selected = selector.selectedKeys();
            for (Iterator<SelectionKey> iterator = selected.iterator(); iterator.hasNext(); ) {
                SelectionKey key = iterator.next();
                iterator.remove();

                Object attachment = key.attachment();
                if (attachment instanceof Selectable) {
                    Selectable selectable = (Selectable) attachment;
                    if (key.isConnectable()) {
                        executions++;
                        selectable.onConnect();
                    } else if (key.isReadable()) {
                        executions++;
                        selectable.onReadable();
                    } else if (key.isWritable()) {
                        executions++;
                        selectable.onWriteable();
                    }
                }
            }
        }
    }
 
Example 20
Source File: NioSelectorLoop.java    From light-task-scheduler with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

    while (running) {

        try {
            select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            if (selectionKeys.isEmpty()) {
                continue;
            }

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                final SelectionKey key = iterator.next();
                iterator.remove();

                if (!key.isValid()) {
                    continue;
                }

                if (key.isAcceptable()) {
                    doAccept(key);
                }

                if (key.isConnectable()) {
                    doConnect(key);
                }

                if (key.isValid() && key.isReadable()) {
                    doRead(key);
                }

                if (key.isValid() && key.isWritable()) {
                    doWrite(key);
                }
            }

        } catch (Throwable t) {
            LOGGER.warn("Unexpected exception in the selector loop.", t);

            // 睡眠1S, 防止连续的异常导致cpu消耗
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {
            }
        }
    }
}