Example usage for java.nio.channels SelectionKey channel

List of usage examples for java.nio.channels SelectionKey channel

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey channel.

Prototype

public abstract SelectableChannel channel();

Source Link

Document

Returns the channel for which this key was created.

Usage

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

private boolean sendPacket(Packet packet, InetSocketAddress address, SelectionKey selectedKey) {

    boolean result = false;

    try {/*from w w  w  .  j  a  v  a 2s .  c  om*/
        boolean sent = false;

        while (!sent) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }

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

            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                if (key.isValid() && key.isWritable() && key.equals(selectedKey)) {
                    SelectableChannel channel = key.channel();
                    try {
                        if (channel instanceof DatagramChannel) {
                            logger.trace(
                                    "Discovery : Sending packet type '{}' from '{}' to '{}' for '{}' with sequence '{}' and source '{}'",
                                    new Object[] { packet.getClass().getSimpleName(),
                                            ((InetSocketAddress) ((DatagramChannel) channel).getLocalAddress())
                                                    .toString(),
                                            address.toString(), packet.getTarget().getHex(),
                                            packet.getSequence(), Long.toString(packet.getSource(), 16) });
                            ((DatagramChannel) channel).send(packet.bytes(), address);

                            sent = true;
                            result = true;
                        } else if (channel instanceof SocketChannel) {
                            ((SocketChannel) channel).write(packet.bytes());
                        }
                    } catch (Exception e) {
                        logger.error("An exception occurred while writing data : '{}'", e.getMessage());
                    }
                }
            }
        }

    } catch (Exception e) {
        logger.error("An exception occurred while communicating with the light : '{}'", e.getMessage());
    }

    return result;
}

From source file:com.springrts.springls.ServerThread.java

/** Check for incoming messages */
private void readIncomingMessages() {

    Client client = null;//from ww  w  .  j  a v  a 2  s  .c om
    try {
        // non-blocking select, returns immediately regardless of
        // how many keys are ready
        readSelector.selectNow();

        // fetch the keys
        Set<SelectionKey> readyKeys = readSelector.selectedKeys();

        // run through the keys and process each one
        while (!readyKeys.isEmpty()) {
            SelectionKey key = readyKeys.iterator().next();
            readyKeys.remove(key);
            SocketChannel channel = (SocketChannel) key.channel();
            client = (Client) key.attachment();
            if (client.isHalfDead()) {
                continue;
            }
            readBuffer.clear();

            client.setTimeOfLastReceive(System.currentTimeMillis());

            // read from the channel into our buffer
            long nBytes = channel.read(readBuffer);
            client.addReceived(nBytes);

            // basic anti-flood protection
            FloodProtectionService floodProtection = getContext().getService(FloodProtectionService.class);
            if ((floodProtection != null) && floodProtection.isFlooding(client)) {
                continue;
            }

            // check for end-of-stream
            if (nBytes == -1) {
                LOG.debug("Socket disconnected - killing client");
                channel.close();
                // this will also close the socket channel
                getContext().getClients().killClient(client);
            } else {
                // use a CharsetDecoder to turn those bytes into a string
                // and append it to the client's StringBuilder
                readBuffer.flip();
                String str = getContext().getServer().getAsciiDecoder().decode(readBuffer).toString();
                readBuffer.clear();
                client.appendToRecvBuf(str);

                // TODO move this to Client#appendToRecvBuf(String)
                // check for a full line
                String line = client.readLine();
                while (line != null) {
                    executeCommandWrapper(line, client);

                    if (!client.isAlive()) {
                        // in case the client was killed within the
                        // executeCommand() method
                        break;
                    }
                    line = client.readLine();
                }
            }
        }
    } catch (IOException ioex) {
        LOG.info("exception during select(): possibly due to force disconnect. Killing the client ...");
        if (client != null) {
            getContext().getClients().killClient(client, "Quit: connection lost");
        }
        LOG.debug("... the exception was:", ioex);
    }
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private final void processAccept(SelectionKey key) throws Exception {

    // Check TCP/IP access
    if (hosts != null || addresses != null) {
        Socket socket = ((SocketChannel) key.channel()).socket();
        InetAddress inetAddress = socket.getInetAddress();
        if (hosts != null) {
            String host = inetAddress.getHostName();
            if (host == null || host.length() == 0 || host.equals("127.0.0.1")) {
                host = "localhost";
            } else {
                host = host.toLowerCase();
                if (host.equals("localhost.localdomain")) {
                    host = "localhost";
                }/*from  ww  w .  j  av a  2 s . co m*/
            }
            if (!isHostMatch(host)) {
                throw new Exception("Connection refused, forbidden hostname (" + host + ")!");
            }
        }
        if (addresses != null) {
            String address = inetAddress.getHostAddress();
            if (address == null || address.length() == 0) {
                address = "127.0.0.1";
            }
            if (!isAddressMatch(address)) {
                throw new Exception("Connection refused, forbidden IP-address (" + address + ")!");
            }
        }
    }
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Disconnects all clients from this server
 *///from  w  w w  . j  av  a2s  .  c om
private void processDisconnect() {
    Iterator it = selector.keys().iterator();
    while (it.hasNext()) {
        SelectionKey sk = (SelectionKey) it.next();
        SelectableChannel channel = (SelectableChannel) sk.channel();
        if (channel instanceof SocketChannel) {
            cancel(sk);
        }
    }
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Cancel SelesctionKey, close Channel and "free" the attachment
 *//*  w ww  .  j  a v  a  2  s. c o  m*/
private void cancel(SelectionKey sk) {

    sk.cancel();

    SelectableChannel channel = (SelectableChannel) sk.channel();

    try {
        channel.close();
    } catch (IOException err) {
        LOG.error("Channel.close()", err);
    }

    DaapConnection connection = (DaapConnection) sk.attachment();

    if (connection != null) {

        DaapSession session = connection.getSession(false);
        if (session != null) {
            sessionIds.remove(session.getSessionId());
        }

        connection.close();

        if (connection.isDaapConnection()) {
            connections.remove(connection);
        } else if (connection.isAudioStream()) {
            streams.remove(connection);
        }
    }
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Notify all clients about an update of the Library
 *//*from w  w w  .jav a2  s.com*/
private void processUpdate() {

    Set keys = selector.keys();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        SelectionKey sk = (SelectionKey) it.next();
        SelectableChannel channel = (SelectableChannel) sk.channel();

        if (channel instanceof SocketChannel) {

            DaapConnection connection = (DaapConnection) sk.attachment();

            if (connection.isDaapConnection()) {
                try {
                    connection.update();
                    if (sk.isValid()) {
                        try {
                            sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                        } catch (CancelledKeyException err) {
                            cancel(sk);
                            LOG.error("SelectionKey.interestOps()", err);
                        }
                    }
                } catch (ClosedChannelException err) {
                    cancel(sk);
                    LOG.error("DaapConnection.update()", err);
                } catch (IOException err) {
                    cancel(sk);
                    LOG.error("DaapConnection.update()", err);
                }
            }
        }
    }
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

public void shutdown(final long period, final TimeUnit timeUnit) {
    channelDispatcher.stop();/*from ww  w .j  a  va  2 s .  com*/
    for (SelectionKey selectionKey : socketChannelSelector.keys()) {
        final AbstractChannelReader reader = (AbstractChannelReader) selectionKey.attachment();
        selectionKey.cancel();
        if (reader != null) {
            while (!reader.isClosed()) {
                try {
                    Thread.sleep(channelReaderFrequencyMSecs);
                } catch (InterruptedException e) {
                }
            }
            final ScheduledFuture<?> readerFuture = reader.getScheduledFuture();
            readerFuture.cancel(false);
        }
        IOUtils.closeQuietly(selectionKey.channel()); // should already be closed via reader, but if reader did not exist...
    }
    IOUtils.closeQuietly(socketChannelSelector);

    for (SelectionKey selectionKey : serverSocketSelector.keys()) {
        selectionKey.cancel();
        IOUtils.closeQuietly(selectionKey.channel());
    }
    IOUtils.closeQuietly(serverSocketSelector);
    executor.shutdown();
    try {
        executor.awaitTermination(period, timeUnit);
    } catch (final InterruptedException ex) {
        LOGGER.warn("Interrupted while trying to shutdown executor");
    }
    final int currentBufferPoolSize = bufferPool.size();
    final String warning = (currentBufferPoolSize != initialBufferPoolSize)
            ? "Initial buffer count=" + initialBufferPoolSize + " Current buffer count=" + currentBufferPoolSize
                    + " Could indicate a buffer leak.  Ensure all consumers are executed until they complete."
            : "";
    LOGGER.info("Channel listener shutdown. " + warning);
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Accept an icoming connection//from  w  w w  . j  a va2 s  .c  o  m
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}

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();/*from w  w  w  .  j a  v a2 s. c o  m*/

    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:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Read data//w  w  w . j a va  2s  .  co m
 * 
 * @throws IOException
 */
private void processRead(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    DaapConnectionNIO connection = (DaapConnectionNIO) sk.attachment();
    SocketChannel channel = (SocketChannel) sk.channel();

    boolean keepAlive = false;

    keepAlive = connection.read();

    if (keepAlive) {
        sk.interestOps(connection.interrestOps());
    } else {
        cancel(sk);
    }
}