List of usage examples for java.nio.channels SelectionKey isAcceptable
public final boolean isAcceptable()
From source file:org.pvalsecc.comm.MultiplexedServer.java
public void run() { try {//from w w w .ja v a2 s.com createSocket(); synchronized (socketCreatedLock) { socketCreated = true; socketCreatedLock.notifyAll(); } while (!stop) { int nbKeys = 0; try { nbKeys = selector.select(); } catch (IOException e) { LOGGER.error(e); } if (nbKeys > 0) { Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isAcceptable()) { createNewClientConnection(key); } else if (key.isWritable()) { long startTime = System.nanoTime(); readyToSend(key); timeSending += System.nanoTime() - startTime; } else if (key.isReadable()) { long startTime = System.nanoTime(); readyToReceive(key); timeReceiving += System.nanoTime() - startTime; } it.remove(); } } } } catch (RuntimeException ex) { LOGGER.error("The MultiplexedServer [" + threadName + "] caught an unexpected exception.", ex); fatalErrorReporter.report(ex); } finally { if (selector != null) { for (SelectionKey key : selector.keys()) { SystemUtilities.safeClose(key.channel()); } SystemUtilities.safeClose(selector); } LOGGER.info("[" + threadName + "] inTime=" + UnitUtilities.toElapsedNanoTime(timeReceiving) + " outTime=" + UnitUtilities.toElapsedNanoTime(timeSending) + " in=" + nbBytesReceived + "B out=" + UnitUtilities.toComputerSize(nbBytesSent) + "B inNb=" + nbReceived + " outNb=" + nbSent); } }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void run() { while (!stopped) { try {//from www . j av 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); } } }
From source file:gridool.communication.transport.nio.GridNioServer.java
public void accept(@Nonnull final Selector selector) throws IOException { while (!closed && selector.select() > 0) { for (Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); iter.hasNext();) { SelectionKey key = iter.next(); iter.remove();/*from ww w. j ava 2 s . c om*/ if (!key.isValid()) { // Is key closed? if (LOG.isDebugEnabled()) { LOG.debug("Non valid key was detected. Key is already closed?"); } continue; } if (key.isAcceptable()) { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); handleAccept(serverChannel, selector); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); handleRead(channel, key, sharedReadBuf, notifier, execPool); } } } if (LOG.isInfoEnabled()) { LOG.info("GridNioServer is going to be closed"); } this.closed = true; if (selector.isOpen()) { for (SelectionKey key : selector.keys()) { NIOUtils.close(key); } selector.close(); } }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
private void processSelectedKeys(Set<SelectionKey> keys) throws Exception { Iterator<SelectionKey> itr = keys.iterator(); while (itr.hasNext()) { SelectionKey key = itr.next(); if (key.isReadable()) { processRead(key);//w w w .j a v a2 s . c o m } if (key.isWritable()) { processWrite(key); } if (key.isConnectable()) { processConnect(key); } if (key.isAcceptable()) { ; } itr.remove(); } }
From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java
@Override public void run() { try {// w w w.j a va 2 s . c o m 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:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * The actual NIO run loop/*w ww .java2 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:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();/* w w w.j a v a 2 s .c om*/ CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
protected void onAcceptable() { lock.lock();//from www .j av a 2s . c om try { try { selector.selectNow(); } catch (IOException e) { logger.debug("An exception occurred while selecting: {}", e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); it.remove(); if (selKey.isValid()) { if (selKey.isAcceptable() && selKey == listenerKey) { try { SocketChannel newChannel = listenerChannel.accept(); newChannel.configureBlocking(false); logger.trace("Received a connection request from '{}'", newChannel.getRemoteAddress()); synchronized (selector) { selector.wakeup(); newChannel.register(selector, newChannel.validOps()); } } catch (IOException e) { logger.debug("An exception occurred while accepting a connection on channel '{}': {}", listenerChannel, e.getMessage()); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); } } } } } finally { lock.unlock(); } }
From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // ? while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();//w w w.j ava 2 s .co m if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // ??? if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// ? continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // ??? if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }
From source file:com.taobao.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();//from w w w . java 2 s. co m if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }