Java Code Examples for java.nio.channels.SelectionKey#interestOps()
The following examples show how to use
java.nio.channels.SelectionKey#interestOps() .
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: RCONServer.java From Nukkit with GNU General Public License v3.0 | 6 votes |
private void write(SelectionKey key) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); synchronized (this.sendQueues) { List<RCONPacket> queue = this.sendQueues.get(channel); ByteBuffer buffer = queue.get(0).toBuffer(); try { channel.write(buffer); queue.remove(0); } catch (IOException exception) { key.cancel(); channel.close(); this.rconSessions.remove(channel); this.sendQueues.remove(channel); return; } if (queue.isEmpty()) { this.sendQueues.remove(channel); } key.interestOps(SelectionKey.OP_READ); } }
Example 2
Source File: AbstractNioWorker.java From simple-netty-source with Apache License 2.0 | 6 votes |
protected void setOpWrite(AbstractNioChannel<?> channel) { Selector selector = this.selector; SelectionKey key = channel.channel.keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) == 0) { interestOps |= SelectionKey.OP_WRITE; key.interestOps(interestOps); channel.setRawInterestOpsNow(interestOps); } }
Example 3
Source File: SelectorThread.java From L2jBrasil with GNU General Public License v3.0 | 6 votes |
private final void finishConnection(final SelectionKey key, final MMOConnection<T> con) { try { ((SocketChannel) key.channel()).finishConnect(); } catch (IOException e) { con.getClient().onForcedDisconnection(); closeConnectionImpl(key, con); } // key might have been invalidated on finishConnect() if (key.isValid()) { key.interestOps(key.interestOps() | SelectionKey.OP_READ); key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT); } }
Example 4
Source File: Server.java From stratosphere with Apache License 2.0 | 6 votes |
private void doAsyncWrite(SelectionKey key) throws IOException { Call call = (Call) key.attachment(); if (call == null) { return; } if (key.channel() != call.connection.channel) { throw new IOException("doAsyncWrite: bad channel"); } synchronized (call.connection.responseQueue) { if (processResponse(call.connection.responseQueue, false)) { try { key.interestOps(0); } catch (CancelledKeyException e) { /* * The Listener/reader might have closed the socket. * We don't explicitly cancel the key, so not sure if this will * ever fire. * This warning could be removed. */ LOG.warn("Exception while changing ops : " + e); } } } }
Example 5
Source File: AbstractSelectableChannel.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Registers this channel with the given selector, returning a selection key. * * <p> This method first verifies that this channel is open and that the * given initial interest set is valid. * * <p> If this channel is already registered with the given selector then * the selection key representing that registration is returned after * setting its interest set to the given value. * * <p> Otherwise this channel has not yet been registered with the given * selector, so the {@link AbstractSelector#register register} method of * the selector is invoked while holding the appropriate locks. The * resulting key is added to this channel's key set before being returned. * </p> * * @throws ClosedSelectorException {@inheritDoc} * * @throws IllegalBlockingModeException {@inheritDoc} * * @throws IllegalSelectorException {@inheritDoc} * * @throws CancelledKeyException {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ public final SelectionKey register(Selector sel, int ops, Object att) throws ClosedChannelException { synchronized (regLock) { if (!isOpen()) throw new ClosedChannelException(); if ((ops & ~validOps()) != 0) throw new IllegalArgumentException(); if (isBlocking()) throw new IllegalBlockingModeException(); SelectionKey k = findKey(sel); if (k != null) { k.interestOps(ops); k.attach(att); } if (k == null) { // New registration synchronized (keyLock) { if (!isOpen()) throw new ClosedChannelException(); k = ((AbstractSelector)sel).register(this, ops, att); addKey(k); } } return k; } }
Example 6
Source File: AbstractConnection.java From tddl5 with Apache License 2.0 | 5 votes |
/** * 打开读事件 */ public void enableRead() { final Lock lock = this.keyLock; lock.lock(); try { SelectionKey key = this.processKey; key.interestOps(key.interestOps() | SelectionKey.OP_READ); } finally { lock.unlock(); } processKey.selector().wakeup(); }
Example 7
Source File: AbstractNioChannel.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
protected final void removeReadOp() { SelectionKey key = selectionKey(); // Check first if the key is still valid as it may be canceled as part of the deregistration 首先检查密钥是否仍然有效,因为它可能作为注销的一部分 // from the EventLoop 从EventLoop // See https://github.com/netty/netty/issues/2104 if (!key.isValid()) { return; } int interestOps = key.interestOps(); if ((interestOps & readInterestOp) != 0) { // only remove readInterestOp if needed 如果需要,只删除readInterestOp key.interestOps(interestOps & ~readInterestOp); } }
Example 8
Source File: AbstractConnection.java From tddl5 with Apache License 2.0 | 5 votes |
/** * 打开写事件 */ private void enableWrite() { final Lock lock = this.keyLock; lock.lock(); try { SelectionKey key = this.processKey; key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); } finally { lock.unlock(); } processKey.selector().wakeup(); }
Example 9
Source File: NIOSocketWR.java From dble with GNU General Public License v2.0 | 5 votes |
private void disableWrite() { try { SelectionKey key = this.processKey; key.interestOps(key.interestOps() & OP_NOT_WRITE); } catch (Exception e) { AbstractConnection.LOGGER.info("can't disable write " + e + " con " + con); } }
Example 10
Source File: ClosableConnection.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void enableWrite(boolean wakeup) { boolean needWakeup = false; try { SelectionKey key = this.processKey; key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); needWakeup = true; } catch (Exception e) { LOGGER.warn("can't enable write: ", e); } if (needWakeup && wakeup) { processKey.selector().wakeup(); } }
Example 11
Source File: SenderKeyHandler.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
/** * Writes messages to a channel associated with the key. * * @param key a key carrying the channel. * @throws IOException if I/O error occurs. */ private void writeMessages(final SelectionKey key) throws IOException { long totalBytesWritten = 0L; final SocketChannel channel = socketChannel(key); for (final Iterator<Message> iter = messages.iterator(); iter.hasNext(); ) { final Message message = iter.next(); // Time stamp the message message.setTimestamp(clock.currentTime()); // Convert the message to a byte array final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); final Frame requestFrame = new Frame(Integer.MAX_VALUE, serializer, Frame.NO_COMPRESSION, 0L, message); requestFrame.write(baos); baos.flush(); final byte[] bytes = baos.toByteArray(); // Write final ByteBuffer buffer = ByteBuffer.wrap(bytes); final int bytesToWrite = buffer.remaining(); final int bytesWritten = write(channel, buffer); totalBytesWritten += bytesWritten; // Process write results if (bytesWritten < bytesToWrite) { // Did not finish writing, register interest in write key.interestOps(OP_WRITE | OP_READ); // Register leftover buffer leftover = buffer; // Exit message writing loop to wait for write readiness break; } else { // //noinspection ControlFlowStatementWithoutBraces // if (LOG.isDebugEnabled()) LOG.debug("Sent: " + message); // NOPMD // Completely wrote the message, process next iter.remove(); } } // Register activity because handleWrite() can // be called outside of the main selector cycle if (totalBytesWritten == 0) { registerInactivity(key); } else { registerActivity(); } }
Example 12
Source File: NioUtils.java From netcrusher-java with Apache License 2.0 | 4 votes |
public static void setupInterestOps(SelectionKey selectionKey, int options) { if ((selectionKey.interestOps() & options) != options) { selectionKey.interestOps(selectionKey.interestOps() | options); } }
Example 13
Source File: PackedBufferManager.java From incubator-retired-htrace with Apache License 2.0 | 4 votes |
/** * Send the provided ByteBuffer objects. * * We use non-blocking I/O because Java does not provide write timeouts. * Without a write timeout, the socket could get hung and we'd never recover. * We also use the GatheringByteChannel#write method which calls the pread() * system call under the covers. This ensures that even if TCP_NODELAY is on, * we send the minimal number of packets. */ private void doSend(SelectionKey sockKey, ByteBuffer[] bufs) throws IOException { long totalWritten = 0; sockKey.interestOps(SelectionKey.OP_WRITE); SocketChannel sock = (SocketChannel)sockKey.attachment(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (true) { selector.select(remainingMs); int firstBuf = 0; for (SelectionKey key : selector.selectedKeys()) { if (key.isWritable()) { long written = sock.write(bufs, firstBuf, bufs.length - firstBuf); if (LOG.isTraceEnabled()) { LOG.trace("Sent " + written + " bytes to " + conf.endpointStr); } totalWritten += written; } } while (true) { if (firstBuf == bufs.length) { if (LOG.isTraceEnabled()) { LOG.trace("Finished sending " + totalWritten + " bytes to " + conf.endpointStr); } return; } if (bufs[firstBuf].remaining() > 0) { break; } firstBuf++; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }
Example 14
Source File: ClosableConnection.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 4 votes |
protected void disableRead() { SelectionKey key = this.processKey; key.interestOps(key.interestOps() & OP_NOT_READ); }
Example 15
Source File: SelectorImpl.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
private void enableInterestOps() { synchronized (interestOpsList) { int listSize = interestOpsList.size(); if (listSize > 0) { if (orb.transportDebugFlag) { dprint(".enableInterestOps:->"); } SelectionKey selectionKey = null; SelectionKeyAndOp keyAndOp = null; int keyOp, selectionKeyOps = 0; for (int i = 0; i < listSize; i++) { keyAndOp = (SelectionKeyAndOp)interestOpsList.get(i); selectionKey = keyAndOp.selectionKey; // Need to check if the SelectionKey is valid because a // connection's SelectionKey could be put on the list to // have its OP enabled and before it's enabled be reclaimed. // Otherwise, the enabling of the OP will throw an exception // here and exit this method an potentially not enable all // registered ops. // // So, we ignore SelectionKeys that are invalid. They will get // cleaned up on the next Selector.select() call. if (selectionKey.isValid()) { if (orb.transportDebugFlag) { dprint(".enableInterestOps: " + keyAndOp); } keyOp = keyAndOp.keyOp; selectionKeyOps = selectionKey.interestOps(); selectionKey.interestOps(selectionKeyOps | keyOp); } } interestOpsList.clear(); if (orb.transportDebugFlag) { dprint(".enableInterestOps:<-"); } } } }
Example 16
Source File: SocketNioSend.java From Tomcat8-Source-Read with MIT License | 4 votes |
public static void main(String[] args) throws Exception { Selector selector = Selector.open(); Member mbr = new MemberImpl("localhost", 9999, 0); ChannelData data = new ChannelData(); data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE); data.setAddress(mbr); byte[] buf = new byte[8192 * 4]; data.setMessage(new XByteBuffer(buf,false)); buf = XByteBuffer.createDataPackage(data); int len = buf.length; BigDecimal total = new BigDecimal((double)0); BigDecimal bytes = new BigDecimal((double)len); NioSender sender = new NioSender(); sender.setDestination(mbr); sender.setDirectBuffer(true); sender.setSelector(selector); sender.setTxBufSize(1024*1024); sender.connect(); sender.setMessage(buf); System.out.println("Writing to 9999"); long start = 0; double mb = 0; boolean first = true; int count = 0; DecimalFormat df = new DecimalFormat("##.00"); while (count<100000) { if (first) { first = false; start = System.currentTimeMillis(); } sender.setMessage(buf); int selectedKeys = 0; try { selectedKeys = selector.select(0); } catch (Exception e) { e.printStackTrace(); continue; } if (selectedKeys == 0) { continue; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); try { int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); if (sender.process(sk, false)) { total = total.add(bytes); sender.reset(); sender.setMessage(buf); mb += ( (double) len) / 1024 / 1024; if ( ( (++count) % 10000) == 0) { long time = System.currentTimeMillis(); double seconds = ( (double) (time - start)) / 1000; System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes."); } } } catch (Throwable t) { t.printStackTrace(); return; } } selector.selectedKeys().clear(); } System.out.println("Complete, sleeping 15 seconds"); Thread.sleep(15000); }
Example 17
Source File: AbstractNioChannel.java From netty-4.1.22 with Apache License 2.0 | 4 votes |
private boolean isFlushPending() { SelectionKey selectionKey = selectionKey(); return selectionKey.isValid() && (selectionKey.interestOps() & SelectionKey.OP_WRITE) != 0; }
Example 18
Source File: SocketNioValidateSend.java From Tomcat7.0.67 with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { Selector selector; synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 selector = Selector.open(); } Member mbr = new MemberImpl("localhost", 9999, 0); byte seq = 0; byte[] buf = new byte[50000]; Arrays.fill(buf,seq); int len = buf.length; BigDecimal total = new BigDecimal((double)0); BigDecimal bytes = new BigDecimal((double)len); NioSender sender = new NioSender(); sender.setDestination(mbr); sender.setDirectBuffer(true); sender.setSelector(selector); sender.connect(); sender.setMessage(buf); System.out.println("Writing to 9999"); long start = 0; double mb = 0; boolean first = true; int count = 0; DecimalFormat df = new DecimalFormat("##.00"); while (count<100000) { if (first) { first = false; start = System.currentTimeMillis(); } sender.setMessage(buf); int selectedKeys = 0; try { selectedKeys = selector.select(0); } catch (Exception e) { e.printStackTrace(); continue; } if (selectedKeys == 0) { continue; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); try { int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); if (sender.process(sk, false)) { total = total.add(bytes); sender.reset(); seq++; Arrays.fill(buf,seq); sender.setMessage(buf); mb += ( (double) len) / 1024 / 1024; if ( ( (++count) % 10000) == 0) { long time = System.currentTimeMillis(); double seconds = ( (double) (time - start)) / 1000; System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes."); } } } catch (Throwable t) { t.printStackTrace(); return; } } } System.out.println("Complete, sleeping 15 seconds"); Thread.sleep(15000); }
Example 19
Source File: SocketNioValidateSend.java From tomcatsrc with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { Selector selector; synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 selector = Selector.open(); } Member mbr = new MemberImpl("localhost", 9999, 0); byte seq = 0; byte[] buf = new byte[50000]; Arrays.fill(buf,seq); int len = buf.length; BigDecimal total = new BigDecimal((double)0); BigDecimal bytes = new BigDecimal((double)len); NioSender sender = new NioSender(); sender.setDestination(mbr); sender.setDirectBuffer(true); sender.setSelector(selector); sender.connect(); sender.setMessage(buf); System.out.println("Writing to 9999"); long start = 0; double mb = 0; boolean first = true; int count = 0; DecimalFormat df = new DecimalFormat("##.00"); while (count<100000) { if (first) { first = false; start = System.currentTimeMillis(); } sender.setMessage(buf); int selectedKeys = 0; try { selectedKeys = selector.select(0); } catch (Exception e) { e.printStackTrace(); continue; } if (selectedKeys == 0) { continue; } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey sk = it.next(); it.remove(); try { int readyOps = sk.readyOps(); sk.interestOps(sk.interestOps() & ~readyOps); if (sender.process(sk, false)) { total = total.add(bytes); sender.reset(); seq++; Arrays.fill(buf,seq); sender.setMessage(buf); mb += ( (double) len) / 1024 / 1024; if ( ( (++count) % 10000) == 0) { long time = System.currentTimeMillis(); double seconds = ( (double) (time - start)) / 1000; System.out.println("Throughput " + df.format(mb / seconds) + " MB/seconds, total "+mb+" MB, total "+total+" bytes."); } } } catch (Throwable t) { t.printStackTrace(); return; } } } System.out.println("Complete, sleeping 15 seconds"); Thread.sleep(15000); }
Example 20
Source File: NioReplicationTask.java From tomcatsrc with Apache License 2.0 | 3 votes |
/** * 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. * 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. */ public synchronized void serviceChannel (SelectionKey key) { if ( log.isTraceEnabled() ) log.trace("About to service key:"+key); ObjectReader reader = (ObjectReader)key.attachment(); if ( reader != null ) reader.setLastAccess(System.currentTimeMillis()); this.key = key; key.interestOps (key.interestOps() & (~SelectionKey.OP_READ)); key.interestOps (key.interestOps() & (~SelectionKey.OP_WRITE)); }