List of usage examples for java.nio.channels SelectionKey OP_READ
int OP_READ
To view the source code for java.nio.channels SelectionKey OP_READ.
Click Source Link
From source file:idgs.client.TcpClient.java
public void read() throws IOException { channel.register(selector, SelectionKey.OP_READ); select(); }
From source file:com.l2jfree.network.mmocore.ReadWriteThread.java
private void finishConnection(SelectionKey key) { try {/*w ww. j a va2s . c o m*/ ((SocketChannel) key.channel()).finishConnect(); } catch (IOException e) { @SuppressWarnings("unchecked") T con = (T) key.attachment(); closeConnectionImpl(con, true); return; } // key might have been invalidated on finishConnect() if (key.isValid()) { key.interestOps(key.interestOps() | SelectionKey.OP_READ); key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT); } }
From source file:org.apache.nifi.io.nio.ChannelListener.java
/** * Binds to listen for data grams on the given local IPAddress/port * * @param nicIPAddress - if null will listen on wildcard address, which * means datagrams will be received on all local network interfaces. * Otherwise, will bind to the provided IP address associated with some NIC. * @param port - the port to listen on/*from w w w.j av a2 s. c om*/ * @param receiveBufferSize - the number of bytes to request for a receive * buffer from OS * @throws IOException if unable to add channel */ public void addDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize) throws IOException { final DatagramChannel dChannel = createAndBindDatagramChannel(nicIPAddress, port, receiveBufferSize); dChannel.register(socketChannelSelector, SelectionKey.OP_READ); }
From source file:net.sf.cindy.impl.ChannelSession.java
private void onReadable() { try {/* w w w . ja va 2s . c o m*/ readKey.interestOps(readKey.interestOps() & ~SelectionKey.OP_READ); readFromChannel(readChannel); } catch (CancelledKeyException cke) { close(); } catch (ClosedChannelException cce) { close(); } catch (IOException ioe) { dispatchException(ioe); close(); } catch (Exception e) { dispatchException(e); } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java
private void dispatch() throws IOException { logger.debug("try dispatch"); SelectionKey key = null;//from w ww . ja v a 2s. c o m for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) { key = request.getChannel().keyFor(selector); if (key != null) { // if ((request.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { key.interestOps(SelectionKey.OP_WRITE); request.clearOps(SelectionKey.OP_WRITE); } else if ((request.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { key.interestOps(SelectionKey.OP_READ); request.clearOps(SelectionKey.OP_READ); } } } isWeakuped.set(false); if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) { return; } Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); iterator.remove(); try { if (!key.isValid()) { continue; } else if (key.isAcceptable()) { onAccept(key); } else if (key.isReadable()) { //readerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_READ)); onRead(key); } else if (key.isWritable()) { //writerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_WRITE)); onWrite(key); } } catch (IOException e) { // opsChangeRequstMap.remove((SocketChannel) key.channel()); Session session = (Session) key.attachment(); if (session != null) { session.onException(e); // Session sessionManager.freeSession(session); } key.cancel(); key.channel().close(); e.printStackTrace(); logger.error("OOPSException", e); } } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java
private boolean connect() { try {//from w ww . j a v a 2s . c o m state.set(NetworkStateEnum.NETWORK_STATE_CONNECTING.value); socketChannel = SocketChannel.open(); // socketChannel.connect(new InetSocketAddress(hostName, port)); // ?? socketChannel.configureBlocking(false); selector = Selector.open(); socketChannel.register(selector, SelectionKey.OP_READ); opsChangeRequest = new SocketChannelOPSChangeRequest(socketChannel, 0); // state.set(NetworkStateEnum.NETWORK_STATE_CONNECTED.value); logger.warn(String.format("Slave connected to %s", hostName)); return true; } catch (IOException e) { logger.error("OOPSException", e); } state.set(NetworkStateEnum.NETWORK_STATE_DISCONNECT.value); return false; }
From source file:com.buaa.cfs.net.SocketIOWithTimeout.java
private static String timeoutExceptionString(SelectableChannel channel, long timeout, int ops) { String waitingFor;/* w w w. j a v a2s . com*/ switch (ops) { case SelectionKey.OP_READ: waitingFor = "read"; break; case SelectionKey.OP_WRITE: waitingFor = "write"; break; case SelectionKey.OP_CONNECT: waitingFor = "connect"; break; default: waitingFor = "" + ops; } return timeout + " millis timeout while " + "waiting for channel to be ready for " + waitingFor + ". ch : " + channel; }
From source file:voldemort.server.niosocket.NioSelectorManager.java
@Override protected void processEvents() { try {//from w w w . java 2s. c o m SocketChannel socketChannel = null; while ((socketChannel = socketChannelQueue.poll()) != null) { if (isClosed.get()) { if (logger.isInfoEnabled()) logger.debug("Closed, exiting for " + endpoint); break; } try { if (logger.isDebugEnabled()) logger.debug("Registering connection from " + socketChannel.socket().getPort()); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setReuseAddress(true); socketChannel.socket().setSendBufferSize(socketBufferSize); if (socketChannel.socket().getReceiveBufferSize() != this.socketBufferSize) if (logger.isDebugEnabled()) logger.debug("Requested socket receive buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getReceiveBufferSize() + " bytes."); if (socketChannel.socket().getSendBufferSize() != this.socketBufferSize) if (logger.isDebugEnabled()) logger.debug("Requested socket send buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getSendBufferSize() + " bytes."); socketChannel.configureBlocking(false); AsyncRequestHandler attachment = new AsyncRequestHandler(selector, socketChannel, requestHandlerFactory, socketBufferSize, numActiveConnections); if (!isClosed.get()) { socketChannel.register(selector, SelectionKey.OP_READ, attachment); numActiveConnections.increment(); } } catch (ClosedSelectorException e) { if (logger.isDebugEnabled()) logger.debug("Selector is closed, exiting"); close(); break; } catch (Exception e) { if (logger.isEnabledFor(Level.ERROR)) logger.error(e.getMessage(), e); } } } catch (Exception e) { if (logger.isEnabledFor(Level.ERROR)) logger.error(e.getMessage(), e); } }
From source file:org.apache.catalina.cluster.tcp.TcpReplicationThread.java
/** * The actual code which drains the channel associated with * the given key. This method assumes the key has been * modified prior to invocation to turn off selection * interest in OP_READ. When this method completes it * re-enables OP_READ and calls wakeup() on the selector * so the selector will resume watching this channel. */// www . j a v a 2 s . co m private void drainChannel(SelectionKey key) throws Exception { boolean packetReceived = false; SocketChannel channel = (SocketChannel) key.channel(); int count; buffer.clear(); // make buffer empty ObjectReader reader = (ObjectReader) key.attachment(); // loop while data available, channel is non-blocking while ((count = channel.read(buffer)) > 0) { buffer.flip(); // make buffer readable int pkgcnt = reader.append(buffer.array(), 0, count); buffer.clear(); // make buffer empty } //check to see if any data is available int pkgcnt = reader.execute(); while (pkgcnt > 0) { if (synchronous) { sendAck(key, channel); } //end if pkgcnt--; } if (count < 0) { // close channel on EOF, invalidates the key channel.close(); return; } // resume interest in OP_READ, OP_WRITE key.interestOps(key.interestOps() | SelectionKey.OP_READ); // cycle the selector so this key is active again key.selector().wakeup(); }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void run() { while (!stopped) { try {//from w w w. ja v a 2s . c o m int selected = selector.select(); // if stopped the selector could already be closed which would result in a ClosedSelectorException if (selected > 0 && !stopped) { Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator(); // if stopped we don't want to modify the keys because close() may still be in progress while (selectorKeys.hasNext() && !stopped) { SelectionKey key = selectorKeys.next(); selectorKeys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { // Handle new connections coming in final ServerSocketChannel channel = (ServerSocketChannel) key.channel(); final SocketChannel socketChannel = channel.accept(); // Check for available connections if (currentConnections.incrementAndGet() > maxConnections) { currentConnections.decrementAndGet(); logger.warn("Rejecting connection from {} because max connections has been met", new Object[] { socketChannel.getRemoteAddress().toString() }); IOUtils.closeQuietly(socketChannel); continue; } logger.debug("Accepted incoming connection from {}", new Object[] { socketChannel.getRemoteAddress().toString() }); // Set socket to non-blocking, and register with selector socketChannel.configureBlocking(false); SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); // Prepare the byte buffer for the reads, clear it out ByteBuffer buffer = bufferPool.poll(); buffer.clear(); buffer.mark(); // If we have an SSLContext then create an SSLEngine for the channel SSLSocketChannel sslSocketChannel = null; if (sslContext != null) { final SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); switch (clientAuth) { case REQUIRED: sslEngine.setNeedClientAuth(true); break; case WANT: sslEngine.setWantClientAuth(true); break; case NONE: sslEngine.setNeedClientAuth(false); sslEngine.setWantClientAuth(false); break; } sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel); } // Attach the buffer and SSLSocketChannel to the key SocketChannelAttachment attachment = new SocketChannelAttachment(buffer, sslSocketChannel); readKey.attach(attachment); } else if (key.isReadable()) { // Clear out the operations the select is interested in until done reading key.interestOps(0); // Create a handler based on the protocol and whether an SSLEngine was provided or not final Runnable handler; if (sslContext != null) { handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events, logger); } else { handler = handlerFactory.createHandler(key, this, charset, eventFactory, events, logger); } // run the handler executor.execute(handler); } } } // Add back all idle sockets to the select SelectionKey key; while ((key = keyQueue.poll()) != null) { key.interestOps(SelectionKey.OP_READ); } } catch (IOException e) { logger.error("Error accepting connection from SocketChannel", e); } } }