Search in sources :

Example 16 with DatagramChannel

use of java.nio.channels.DatagramChannel in project nifi by apache.

the class ChannelListener method createAndBindDatagramChannel.

private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize) throws IOException {
    final DatagramChannel dChannel = DatagramChannel.open();
    dChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to " + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer");
        }
    }
    dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dChannel.bind(new InetSocketAddress(nicIPAddress, port));
    return dChannel;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel)

Example 17 with DatagramChannel

use of java.nio.channels.DatagramChannel in project nifi by apache.

the class ChannelListener method addDatagramChannel.

/**
 * Binds to listen for data grams on the given local IPAddress/port and
 * restricts receipt of datagrams to those from the provided host and port,
 * must specify both. This improves performance for datagrams coming from a
 * sender that is known a-priori.
 *
 * @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. This is used to provide a well-known
 * destination for a sender.
 * @param receiveBufferSize - the number of bytes to request for a receive
 * buffer from OS
 * @param sendingHost - the hostname, or IP address, of the sender of
 * datagrams. Only datagrams from this host will be received. If this is
 * null the wildcard ip is used, which means datagrams may be received from
 * any network interface on the local host.
 * @param sendingPort - the port used by the sender of datagrams. Only
 * datagrams from this port will be received.
 * @throws IOException if unable to add channel
 */
public void addDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize, final String sendingHost, final Integer sendingPort) throws IOException {
    if (sendingHost == null || sendingPort == null) {
        addDatagramChannel(nicIPAddress, port, receiveBufferSize);
        return;
    }
    final DatagramChannel dChannel = createAndBindDatagramChannel(nicIPAddress, port, receiveBufferSize);
    dChannel.connect(new InetSocketAddress(sendingHost, sendingPort));
    dChannel.register(socketChannelSelector, SelectionKey.OP_READ);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramChannel(java.nio.channels.DatagramChannel)

Example 18 with DatagramChannel

use of java.nio.channels.DatagramChannel in project opennms by OpenNMS.

the class SyslogdImplementationsIT method doTestSyslogd.

private void doTestSyslogd(SyslogReceiver receiver) throws Exception {
    Thread listener = new Thread(receiver);
    listener.start();
    Thread.sleep(3000);
    final int eventCount = 100;
    List<Integer> foos = new ArrayList<>();
    for (int i = 0; i < eventCount; i++) {
        int eventNum = Double.valueOf(Math.random() * 10000).intValue();
        foos.add(eventNum);
    }
    m_eventCounter.setAnticipated(eventCount);
    String testPduFormat = "2010-08-19 localhost foo%d: load test %d on tty1";
    /*
        SyslogClient sc = new SyslogClient(null, 10, SyslogClient.LOG_USER, addr("127.0.0.1"));
        // Test by directly invoking the SyslogConnection task
        System.err.println("Starting to send packets");
        final long start = System.currentTimeMillis();
        for (int i = 0; i < eventCount; i++) {
            int foo = foos.get(i);
            DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo));
            WaterfallExecutor.waterfall(m_executorService, new SyslogConnection(pkt, m_config));
        }

        // Test by sending over a java.net socket
        final DatagramSocket socket = new DatagramSocket();
        System.err.println("Starting to send packets");
        final long start = System.currentTimeMillis();
        for (int i = 0; i < eventCount; i++) {
            int foo = foos.get(i);
            DatagramPacket pkt = sc.getPacket(SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo));
            socket.send(pkt);
        }
        socket.close();
        */
    // Test by sending over an NIO channel
    SocketAddress address = new InetSocketAddress(InetAddressUtils.getLocalHostAddress(), SyslogClient.PORT);
    final DatagramChannel channel = DatagramChannel.open();
    final ByteBuffer buffer = ByteBuffer.allocate(SyslogConnection.MAX_PACKET_SIZE);
    buffer.clear();
    System.err.println("Starting to send packets");
    final long start = System.currentTimeMillis();
    for (int i = 0; i < eventCount; i++) {
        int foo = foos.get(i);
        buffer.put(SyslogClient.getPacketPayload(SyslogClient.LOG_USER, null, SyslogClient.LOG_DEBUG, String.format(testPduFormat, foo, foo)));
        buffer.flip();
        channel.send(buffer, address);
        buffer.clear();
    }
    channel.close();
    long mid = System.currentTimeMillis();
    System.err.println(String.format("Sent %d packets in %d milliseconds", eventCount, mid - start));
    m_eventCounter.waitForFinish(120000);
    long end = System.currentTimeMillis();
    System.err.println(String.format("Events expected: %d, events received: %d", eventCount, m_eventCounter.getCount()));
    final long total = (end - start);
    final double eventsPerSecond = (eventCount * 1000.0 / total);
    System.err.println(String.format("total time: %d, wait time: %d, events per second: %8.4f", total, (end - mid), eventsPerSecond));
    listener.interrupt();
    listener.join();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) DatagramChannel(java.nio.channels.DatagramChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer)

Example 19 with DatagramChannel

use of java.nio.channels.DatagramChannel in project java-design-patterns by iluwatar.

the class NioDatagramChannel method read.

/**
 * Reads and returns a {@link DatagramPacket} from the underlying channel.
 *
 * @return the datagram packet read having the sender address.
 */
@Override
public DatagramPacket read(SelectionKey key) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    SocketAddress sender = ((DatagramChannel) key.channel()).receive(buffer);
    /*
     * It is required to create a DatagramPacket because we need to preserve which socket address
     * acts as destination for sending reply packets.
     */
    buffer.flip();
    DatagramPacket packet = new DatagramPacket(buffer);
    packet.setSender(sender);
    return packet;
}
Also used : DatagramChannel(java.nio.channels.DatagramChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer)

Example 20 with DatagramChannel

use of java.nio.channels.DatagramChannel in project GwellDemo by dxsdyhm.

the class ShakeTask method run.

@Override
public void run() {
    //开始扫描了
    handler.sendEmptyMessage(ShakeManager.HANDLE_ID_SEARCH_START);
    isRun = true;
    try {
        selector = Selector.open();
        channel = DatagramChannel.open();
        //设置非堵塞
        channel.configureBlocking(false);
        server = channel.socket();
        server.bind(new InetSocketAddress(port));
        channel.register(selector, SelectionKey.OP_READ);
        ByteBuffer receiveBuffer = ByteBuffer.allocate(256);
        new Thread() {

            @Override
            public void run() {
                try {
                    int times = 0;
                    broadcast = new DatagramSocket();
                    broadcast.setBroadcast(true);
                    Log.e("leleshaking", "isRun=" + isRun + "--" + "times=" + times);
                    while (times < SEND_TIMES) {
                        if (!isRun) {
                            return;
                        }
                        times++;
                        Log.e("my", "shake thread send broadcast.");
                        ShakeData data = new ShakeData();
                        data.setCmd(ShakeData.Cmd.GET_DEVICE_LIST);
                        DatagramPacket packet = new DatagramPacket(ShakeData.getBytes(data), ShakeData.getBytes(data).length, InetAddress.getByName("255.255.255.255"), port);
                        broadcast.send(packet);
                        Thread.sleep(1000);
                    }
                    Log.e("my", "shake thread broadcast end.");
                } catch (Exception e) {
                    Log.e("leleshaking", e.toString());
                    e.printStackTrace();
                } finally {
                    try {
                        broadcast.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ShakeManager.getInstance().stopShaking();
                }
            }
        }.start();
        while (isRun) {
            int n = selector.select(100);
            if (n > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                for (SelectionKey key : keys) {
                    keys.remove(key);
                    if (key.isReadable()) {
                        DatagramChannel dc = (DatagramChannel) key.channel();
                        InetSocketAddress client = (InetSocketAddress) dc.receive(receiveBuffer);
                        key.interestOps(SelectionKey.OP_READ);
                        receiveBuffer.flip();
                        ShakeData data = ShakeData.getShakeData(receiveBuffer);
                        switch(data.getCmd()) {
                            case ShakeData.Cmd.RECEIVE_DEVICE_LIST:
                                if (data.getError_code() == 1) {
                                    Message msg = new Message();
                                    msg.obj = data;
                                    msg.what = ShakeManager.HANDLE_ID_RECEIVE_DEVICE_INFO;
                                    Bundle bundle = new Bundle();
                                    bundle.putString("ip", client.getAddress().getHostAddress() + "");
                                    msg.setData(bundle);
                                    handler.sendMessage(msg);
                                    break;
                                } else {
                                }
                                receiveBuffer.clear();
                        }
                    }
                }
            }
        }
        Log.e("my", "shake thread end.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e("leleshaking", e.toString());
        e.printStackTrace();
    } finally {
        ShakeManager.getInstance().stopShaking();
        if (null != handler) {
            handler.sendEmptyMessage(ShakeManager.HANDLE_ID_APDEVICE_END);
        }
        try {
            server.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            selector.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) Message(android.os.Message) InetSocketAddress(java.net.InetSocketAddress) Bundle(android.os.Bundle) DatagramChannel(java.nio.channels.DatagramChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket)

Aggregations

DatagramChannel (java.nio.channels.DatagramChannel)214 InetSocketAddress (java.net.InetSocketAddress)92 ByteBuffer (java.nio.ByteBuffer)71 IOException (java.io.IOException)58 MembershipKey (java.nio.channels.MembershipKey)22 DatagramSocket (java.net.DatagramSocket)21 SocketAddress (java.net.SocketAddress)21 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 SocketChannel (java.nio.channels.SocketChannel)17 SelectionKey (java.nio.channels.SelectionKey)16 InetAddress (java.net.InetAddress)13 Selector (java.nio.channels.Selector)13 Test (org.junit.Test)11 SocketException (java.net.SocketException)9 ClosedChannelException (java.nio.channels.ClosedChannelException)9 Histogram (org.HdrHistogram.Histogram)8 CancelledKeyException (java.nio.channels.CancelledKeyException)7 DatagramPacket (java.net.DatagramPacket)5 NetworkInterface (java.net.NetworkInterface)5 ArrayList (java.util.ArrayList)5