Example usage for java.nio.channels SelectionKey OP_READ

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

Introduction

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

Prototype

int OP_READ

To view the source code for java.nio.channels SelectionKey OP_READ.

Click Source Link

Document

Operation-set bit for read operations.

Usage

From source file:net.socket.nio.TimeClientHandle.java

private void doConnect() throws IOException {
    // ?????//from   w  w w  .j  a v a  2s. com
    if (socketChannel.connect(new InetSocketAddress(host, port))) {
        socketChannel.register(selector, SelectionKey.OP_READ);
        doWrite(socketChannel);
    } else {
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
    }
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void startUp() throws Exception {
    selector = Selector.open();/*w w w.j ava  2s  .  com*/

    for (DatagramChannel channel : sendQueue.keySet()) {
        channel.register(selector, SelectionKey.OP_READ);
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.DatagramChannelDispatcher.java

@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
    stopped = false;/*from   w  ww  . j  av a  2s . com*/
    datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);

    if (maxBufferSize > 0) {
        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
        final int actualReceiveBufSize = datagramChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < maxBufferSize) {
            logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize
                    + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }

    // we don't have to worry about nicAddress being null here because InetSocketAddress already handles it
    datagramChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    datagramChannel.socket().bind(new InetSocketAddress(nicAddress, port));

    // if a sending host and port were provided then connect to that specific address to only receive
    // datagrams from that host/port, otherwise we can receive datagrams from any host/port
    if (sendingHost != null && sendingPort != null) {
        datagramChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
    }

    selector = Selector.open();
    datagramChannel.register(selector, SelectionKey.OP_READ);
}

From source file:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java

protected void read(SelectionKey selectionKey, Consumer<List<String>> callback,
        Consumer<Exception> exceptionHandler) {
    try {//from w  ww . j a  v a  2  s .  c o  m
        if (!selectionKey.isValid() || !selectionKey.isReadable())
            return;
        byteBuffer.clear();
        int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer);
        if (bytesRead < 0) {
            LOG.warn(
                    "End of stream reached.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream"));
            return;
        }
        byteBuffer.flip();
        if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) {
            LOG.error("Max message size of " + maxMessageSize
                    + " bytes exceeded.  Deregistering interest in reads on the selection key invoking exception handler.");
            invokeExceptionHandler(selectionKey, exceptionHandler,
                    new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded"));
            return;
        }
        while (byteBuffer.hasRemaining())
            messageBuffer.write(byteBuffer.get());
        String messagesString = messageBuffer.toString(charset);
        messageBuffer.reset();
        List<String> messages = new ArrayList<>();
        for (String message : splitter.split(messagesString))
            messages.add(message);
        messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset));
        if (!messages.isEmpty()) {
            selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
            callback.accept(messages);
        }
    } catch (Exception e) {
        LOG.error("ReadDelimitedMessage task failed", e);
        invokeExceptionHandler(selectionKey, exceptionHandler, e);
    }
}

From source file:com.facebook.infrastructure.net.TcpConnection.java

private void registerReadInterest() throws IOException {
    key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_READ);
}

From source file:org.apache.synapse.transport.udp.IODispatcher.java

/**
 * Add a new endpoint. This method creates a new socket listening on
 * the UDP port specified in the endpoint description and makes sure
 * that incoming packets are routed to the specified service.
 * /*from   w  w w. ja  v  a 2  s.c o m*/
 * @param endpoint the endpoint description
 * @throws IOException if the socket could not be created or
 *         registered with the selector
 */
public void addEndpoint(final Endpoint endpoint) throws IOException {
    final DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(endpoint.getPort()));
    channel.configureBlocking(false);
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            channel.register(selector, SelectionKey.OP_READ, endpoint);
        }
    });
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleAccept(final ServerSocketChannel serverChannel, final Selector selector)
        throws IOException {
    final SocketChannel channel = serverChannel.accept();
    if (channel == null) {
        return;/*from w w w .  ja  v  a  2  s  .  co m*/
    }
    channel.configureBlocking(false);
    channel.register(selector, SelectionKey.OP_READ, new GridMessageBuffer());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Accepted a new client connection: " + channel.socket().getRemoteSocketAddress());
    }
}

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  ava  2  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:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Add a new endpoint. This method creates a new socket listening on
 * the UDP port specified in the endpoint description and makes sure
 * that incoming packets are routed to the specified service.
 * /*  w  w  w.j a  va 2  s  .  co  m*/
 * @param endpoint the endpoint description
 * @throws IOException if the socket could not be created or
 *         registered with the selector
 */
public void addEndpoint(final Endpoint endpoint) throws IOException {
    final DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(endpoint.getPort()));
    channel.configureBlocking(false);
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            channel.register(selector, SelectionKey.OP_READ, endpoint);
        }
    });
    log.info("UDP endpoint started on port : " + endpoint.getPort());
}

From source file:net.ymate.platform.serv.nio.datagram.NioUdpServer.java

public synchronized void start() throws IOException {
    if (!__isStarted) {
        __isStarted = true;//  w  w w  .jav  a 2  s  . com
        __eventGroup = new NioEventGroup<NioUdpListener>(__serverCfg, __listener, __codec) {
            @Override
            protected SelectableChannel __doChannelCreate(INioServerCfg cfg) throws IOException {
                DatagramChannel _channel = DatagramChannel.open();
                _channel.configureBlocking(false);
                _channel.socket().bind(new InetSocketAddress(cfg.getServerHost(), cfg.getPort()));
                return _channel;
            }

            @Override
            protected String __doBuildProcessorName() {
                return StringUtils.capitalize(name()).concat("UdpServer-NioEventProcessor-");
            }

            @Override
            protected void __doInitProcessors() throws IOException {
                __processors = new NioEventProcessor[__selectorCount];
                for (int _idx = 0; _idx < __selectorCount; _idx++) {
                    __processors[_idx] = new NioEventProcessor<NioUdpListener>(this,
                            __doBuildProcessorName() + _idx) {
                        @Override
                        protected void __doExceptionEvent(SelectionKey key, final Throwable e) {
                            final INioSession _session = (INioSession) key.attachment();
                            if (_session != null) {
                                __eventGroup.executorService().submit(new Runnable() {
                                    public void run() {
                                        try {
                                            __eventGroup.listener().onExceptionCaught(e, _session);
                                        } catch (Throwable ex) {
                                            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex));
                                        }
                                    }
                                });
                            } else {
                                _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e));
                            }
                        }
                    };
                    __processors[_idx].start();
                }
            }

            @Override
            protected void __doRegisterEvent() throws IOException {
                for (NioEventProcessor _processor : __processors) {
                    _processor.registerEvent(__channel, SelectionKey.OP_READ,
                            new NioSession<NioUdpListener>(this, __channel) {
                                @Override
                                protected int __doChannelRead(ByteBuffer buffer) throws IOException {
                                    SocketAddress _address = ((DatagramChannel) __channel).receive(buffer);
                                    if (_address != null) {
                                        attr(SocketAddress.class.getName(), _address);
                                        return __buffer.remaining();
                                    }
                                    return 0;
                                }

                                @Override
                                protected int __doChannelWrite(ByteBuffer buffer) throws IOException {
                                    SocketAddress _address = attr(SocketAddress.class.getName());
                                    if (_address != null) {
                                        return ((DatagramChannel) __channel).send(buffer, _address);
                                    }
                                    buffer.reset();
                                    return 0;
                                }
                            });
                }
            }
        };
        __eventGroup.start();
        //
        _LOG.info("UdpServer [" + __eventGroup.name() + "] started at " + __serverCfg.getServerHost() + ":"
                + __serverCfg.getPort());
    }
}