List of usage examples for java.nio.channels SelectionKey isReadable
public final boolean isReadable()
From source file:org.apache.catalina.cluster.tcp.ReplicationListener.java
public void listen() throws Exception { doListen = true;//from ww w.ja v a 2 s .c o 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:org.openhab.binding.keba.handler.KeContactHandler.java
protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize) { lock.lock();/*w ww .j a v a 2s. c om*/ try { SelectionKey theSelectionKey = theChannel.keyFor(selector); if (theSelectionKey != null) { synchronized (selector) { try { selector.selectNow(); } catch (IOException e) { logger.error("An exception occurred while selecting: {}", e.getMessage()); } } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); it.remove(); if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) { ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numberBytesRead = 0; boolean error = false; if (selKey == datagramChannelKey) { try { numberBytesRead = theChannel.read(readBuffer); } catch (NotYetConnectedException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The remote host is not yet connected"); error = true; } catch (PortUnreachableException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The remote host is probably not a KEBA EV Charging station"); error = true; } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An IO exception occurred"); error = true; } } if (numberBytesRead == -1) { error = true; } if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID().toString()); try { theChannel.close(); } catch (IOException e) { logger.error("An exception occurred while closing the channel '{}': {}", datagramChannel, e.getMessage()); } onConnectionLost(); } else { readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java
@Override public void run() { try {/* w ww.j a v a 2 s. c om*/ while (__flag) { __selector.select(5 * DateTimeUtils.SECOND); __doRegisterEvent(); Iterator<SelectionKey> _keyIterator = __selector.selectedKeys().iterator(); while (_keyIterator.hasNext()) { SelectionKey _selectionKey = _keyIterator.next(); _keyIterator.remove(); if (_selectionKey.isValid()) { Object _attachment = _selectionKey.attachment(); if (_attachment instanceof INioSession) { ((INioSession) _attachment).touch(); } try { if (_selectionKey.isAcceptable()) { __doAcceptEvent(_selectionKey); } else if (_selectionKey.isConnectable()) { __doConnectEvent(_selectionKey); } else if (_selectionKey.isReadable()) { __doReadEvent(_selectionKey); } else if (_selectionKey.isWritable()) { __doWriteEvent(_selectionKey); } } catch (Throwable e) { __doExceptionEvent(_selectionKey, e); } } } __doClosedEvent(); } } catch (IOException e) { if (__flag) { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } else { _LOG.debug(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } }
From source file:net.jenet.Host.java
short socketWait(short keyType, int timeOut) { try {//w w w . j a va 2 s .co m communicationSelector.select(timeOut); } catch (Exception e) { LOG.error("Error waiting network events", e); return WAIT_ERROR; } for (SelectionKey key : communicationSelector.selectedKeys()) { if (key.isReadable() && keyType == WAIT_RECEIVE) return WAIT_RECEIVE; else if (key.isWritable() && keyType == WAIT_SEND) return WAIT_SEND; } return WAIT_NONE; }
From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java
protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) { lock.lock();/*from w w w.j ava 2 s . c o m*/ try { SelectionKey theSelectionKey = theChannel.keyFor(selector); if (theSelectionKey != null) { synchronized (selector) { try { selector.selectNow(); } catch (IOException e) { logger.error("An exception occurred while selecting: {}", e.getMessage()); } } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) { ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numberBytesRead = 0; boolean error = false; if (selKey == listenerKey) { try { InetSocketAddress clientAddress = (InetSocketAddress) theChannel .receive(readBuffer); if (clientAddress.getAddress().equals(permittedClientAddress)) { logger.debug("Received {} on the listener port from {}", new String(readBuffer.array()), clientAddress); numberBytesRead = readBuffer.position(); } else { logger.warn( "Received data from '{}' which is not the permitted remote address '{}'", clientAddress, permittedClientAddress); return null; } } catch (Exception e) { logger.error( "An exception occurred while receiving data on the listener port: '{}'", e.getMessage()); error = true; } } else { try { numberBytesRead = theChannel.read(readBuffer); } catch (NotYetConnectedException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The remote host is not yet connected"); error = true; } catch (PortUnreachableException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The remote host is probably not a KEBA EV Charging station"); error = true; } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An IO exception occurred"); error = true; } } if (numberBytesRead == -1) { error = true; } if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID().toString()); try { theChannel.close(); } catch (IOException e) { logger.error("An exception occurred while closing the channel '{}': {}", datagramChannel, e.getMessage()); } onConnectionLost(); } else { readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * The actual NIO run loop// ww w.j a va 2 s . c o m * * @throws IOException */ private void process() throws IOException { int n = -1; running = true; update = false; disconnectAll = false; while (running) { try { n = selector.select(TIMEOUT); } catch (NullPointerException err) { continue; } catch (CancelledKeyException err) { continue; } if (!running) { break; } if (disconnectAll) { processDisconnect(); disconnectAll = false; continue; // as all clients were disconnected // there is nothing more to do } if (update) { processUpdate(); update = false; } if (n == 0) continue; Iterator it = selector.selectedKeys().iterator(); while (it.hasNext() && running) { SelectionKey sk = (SelectionKey) it.next(); it.remove(); try { if (sk.isAcceptable()) { processAccept(sk); } else { if (sk.isReadable()) { try { processRead(sk); } catch (IOException err) { cancel(sk); LOG.error("An exception occured in processRead()", err); } } else if (sk.isWritable()) { try { processWrite(sk); } catch (IOException err) { cancel(sk); LOG.error("An exception occured in processWrite()", err); } } } } catch (CancelledKeyException err) { continue; } } } // close() is in finally of run() {} }
From source file:org.openhab.binding.mart.handler.martHandler.java
/** * Reads a buffer from the channel and returns it * A buffer is essentially a block of memory into which you can write data, which * you can then later read again//ww w. j a v a 2s . c om * * @param theChannel * @param bufferSize * @param permittedClientAddress * @return */ protected ByteBuffer Reader(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) { // The lock() method locks the Lock instance so that all threads calling lock() are blocked until unlock() is // executed. lock.lock(); try { // retrieves the channel's key representing its registration with the selector SelectionKey theSelectionKey = theChannel.keyFor(selector); if (theSelectionKey != null) { synchronized (selector) { try { // it selects a set of keys whose corresponding channels are ready for I/O operations. selector.selectNow(); } catch (IOException e) { logger.error("An exception occured while selecting: {}", e.getMessage()); } catch (ClosedSelectorException e) { logger.error("An exception occured while selecting: {}", e.getMessage()); } } // to iterate over the this selector's selected key set Iterator<SelectionKey> iterate = selector.selectedKeys().iterator(); // if iterate has more elements while (iterate.hasNext()) { // represents the key representing the channel's registration with the Selector (selector). SelectionKey selectKey = iterate.next(); iterate.remove(); if (selectKey.isValid() && selectKey.isReadable() && selectKey == theSelectionKey) { // allocate a new byte buffer with 1024 bytes capacity ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numOfBytesRead = 0; boolean error = false; // if the current select key is the key representing the listener's channel registration // with the selector, then read the byte buffer or data from the channel if (selectKey == listenerKey) { try { // receive a datagram via this channel // the channel writes data into the the readBuffer InetSocketAddress clientAddress = (InetSocketAddress) theChannel .receive(readBuffer); // if the returned address given by the receive() is == permitted address if (clientAddress.getAddress().equals(permittedClientAddress)) { logger.debug("Received {} on the listener port from {}", new String(readBuffer.array()), clientAddress); // returns the buffer's position to help as check whether the buffer is // full or not numOfBytesRead = readBuffer.position(); } else { logger.warn( "Received data from '{}' which is not the permitted remote address '{}'", clientAddress, permittedClientAddress); // since it is not a permitted remote address return nothing return null; } } catch (Exception e) { logger.error( "An exception occurred while receiving data on the listener port: '{}'", e.getMessage()); error = true; } // if the selectKey != listenerKey } else { try { // reads a datagram from this channel though the selectKey != listenerKey // reads a data from this channel into the readBuffer or // the channel writes data into the the buffer numOfBytesRead = theChannel.read(readBuffer); } catch (NotYetConnectedException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "The MART adapter is not yet connected"); error = true; } catch (PortUnreachableException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "This is probably not a MART adapter"); error = true; } catch (IOException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "An IO exception occurred"); error = true; } } // if numOfBytesRead == -1 then the channel has reached end of stream if (numOfBytesRead == -1) { error = true; } // if error == true , close the channel and re-establish connection if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID().toString()); try { // close the channel theChannel.close(); } catch (IOException e) { logger.error("An exception occurred while closing the channel '{}': {}", datagramChannel, e.getMessage()); } // re-establish connection onConnectionLost(); // if error == false, } else { // switch the buffer from writing mode into reading mode and return it readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java
/** * Sit in a loop running the following algorthim till exit: * /*from w w w. j a va 2 s . c o m*/ * <pre> * Let Si be a Sym belonging to Bridge B where an inbound packet P is received * Increment received packet count for B. * Record time for the received packet. * Record inboundAddress from where the packet was received * send(B,chan,inboundAddress) * * </pre> * */ public void run() { // Wait for an event one of the registered channels logger.debug("Starting Shuffler"); while (true) { Bridge bridge = null; try { if (initializeSelectors.get()) { initializeSelector(); } selector.select(); while (!workQueue.isEmpty()) { logger.debug("Got a work item"); WorkItem workItem = (WorkItem) workQueue.remove(0); workItem.doWork(); } // Iterate over the set of keys for which events are // available Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey) selectedKeys.next(); // The key must be removed or you can get one way audio ( i.e. will read a // null byte ). // (see issue 2075 ). selectedKeys.remove(); if (!key.isValid()) { if (logger.isDebugEnabled()) { logger.debug("Discarding packet:Key not valid"); } continue; } if (key.isReadable()) { readBuffer.clear(); DatagramChannel datagramChannel = (DatagramChannel) key.channel(); if (!datagramChannel.isOpen()) { if (logger.isDebugEnabled()) { logger.debug("DataShuffler: Datagram channel is closed -- discarding packet."); } continue; } bridge = ConcurrentSet.getBridge(datagramChannel); if (bridge == null) { if (logger.isDebugEnabled()) { logger.debug("DataShuffler: Discarding packet: Could not find bridge"); } continue; } Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel); /* * Note the original hold value and put the transmitter on which this packet was received on hold. */ if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) { if (logger.isDebugEnabled()) { logger.debug( "DataShuffler: Could not find sym for inbound channel -- discarding packet"); } continue; } boolean holdValue = packetReceivedSym.getTransmitter().isOnHold(); packetReceivedSym.getTransmitter().setOnHold(true); InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer); bridge.pakcetsReceived++; if (bridge.getState() != BridgeState.RUNNING) { if (logger.isDebugEnabled()) { logger.debug( "DataShuffler: Discarding packet: Bridge state is " + bridge.getState()); } packetReceivedSym.getTransmitter().setOnHold(holdValue); continue; } if (logger.isTraceEnabled()) { logger.trace("got something on " + datagramChannel.socket().getLocalPort()); } long stamp = getPacketCounter(); send(bridge, datagramChannel, remoteAddress, stamp, false); /* * Reset the old value. */ packetReceivedSym.getTransmitter().setOnHold(holdValue); } } } catch (Exception ex) { logger.error("Unexpected exception occured", ex); if (bridge != null && bridge.sessions != null) { for (Sym rtpSession : bridge.sessions) { rtpSession.close(); } } if (bridge != null) bridge.setState(BridgeState.TERMINATED); continue; } } }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
protected ByteBuffer onReadable(int bufferSize, boolean isSelective) { lock.lock();/*from w ww.j av a2 s. c o m*/ try { synchronized (selector) { try { selector.selectNow(); } catch (IOException e) { logger.error("An exception occurred while selecting: {}", e.getMessage()); } } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); it.remove(); if (selKey.isValid() && selKey.isReadable()) { SocketChannel aSocketChannel = (SocketChannel) selKey.channel(); if ((aSocketChannel.equals(socketChannel) && isSelective) || !isSelective) { ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numberBytesRead = 0; boolean error = false; try { numberBytesRead = aSocketChannel.read(readBuffer); } catch (NotYetConnectedException e) { logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel, e.getMessage()); if (!aSocketChannel.isConnectionPending()) { error = true; } } catch (IOException e) { // If some other I/O error occurs logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel, e.getMessage()); error = true; } if (numberBytesRead == -1) { error = true; } if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID()); try { aSocketChannel.close(); } catch (IOException e1) { logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel, e1.getMessage()); } } else { readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:org.sipfoundry.sipxrelay.DataShuffler.java
/** * Sit in a loop running the following algorthim till exit: * //from w ww . j a v a 2 s .c om * <pre> * Let Si be a Sym belonging to Bridge B where an inbound packet P is received * Increment received packet count for B. * Record time for the received packet. * Record inboundAddress from where the packet was received * send(B,chan,inboundAddress) * * </pre> * */ public void run() { // Wait for an event one of the registered channels logger.debug("Starting Shuffler"); while (true) { Bridge bridge = null; try { if (initializeSelectors.get()) { initializeSelector(); } selector.select(); checkWorkQueue(); // Iterate over the set of keys for which events are // available Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = (SelectionKey) selectedKeys.next(); // The key must be removed or you can get one way audio ( i.e. will read a // null byte ). // (see issue 2075 ). selectedKeys.remove(); if (!key.isValid()) { if (logger.isDebugEnabled()) { logger.debug("Discarding packet:Key not valid"); } continue; } if (key.isReadable()) { readBuffer.clear(); DatagramChannel datagramChannel = (DatagramChannel) key.channel(); if (!datagramChannel.isOpen()) { if (logger.isDebugEnabled()) { logger.debug("DataShuffler: Datagram channel is closed -- discarding packet."); } continue; } bridge = ConcurrentSet.getBridge(datagramChannel); if (bridge == null) { if (logger.isDebugEnabled()) { logger.debug("DataShuffler: Discarding packet: Could not find bridge"); } continue; } Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel); /* * Note the original hold value and put the transmitter on which this packet was received on hold. */ if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) { if (logger.isDebugEnabled()) { logger.debug( "DataShuffler: Could not find sym for inbound channel -- discarding packet"); } continue; } boolean holdValue = packetReceivedSym.getTransmitter().isOnHold(); packetReceivedSym.getTransmitter().setOnHold(true); InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer); bridge.pakcetsReceived++; if (bridge.getState() != BridgeState.RUNNING) { if (logger.isDebugEnabled()) { logger.debug( "DataShuffler: Discarding packet: Bridge state is " + bridge.getState()); } packetReceivedSym.getTransmitter().setOnHold(holdValue); continue; } if (logger.isTraceEnabled()) { logger.trace("got something on " + datagramChannel.socket().getLocalPort()); } long stamp = getPacketCounter(); send(bridge, datagramChannel, remoteAddress, stamp, false); /* * Reset the old value. */ packetReceivedSym.getTransmitter().setOnHold(holdValue); } } } catch (Exception ex) { logger.error("Unexpected exception occured", ex); if (bridge != null && bridge.sessions != null) { for (Sym rtpSession : bridge.sessions) { rtpSession.close(); } } if (bridge != null) bridge.setState(BridgeState.TERMINATED); continue; } } }