java.nio.channels.DatagramChannel

Here are the examples of the java api class java.nio.channels.DatagramChannel taken from open source projects.

1. UseDGWithIPv6#main()

Project: openjdk
File: UseDGWithIPv6.java
public static void main(String[] args) throws IOException {
    ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
    DatagramChannel dgChannel = DatagramChannel.open();
    for (int i = 0; i < targets.length; i++) {
        data.rewind();
        SocketAddress sa = new InetSocketAddress(targets[i], port);
        System.out.println("-------------\nDG_Sending data:" + "\n    remaining:" + data.remaining() + "\n     position:" + data.position() + "\n        limit:" + data.limit() + "\n     capacity:" + data.capacity() + " bytes on DG channel to " + sa);
        try {
            int n = dgChannel.send(data, sa);
            System.out.println("DG_Sent " + n + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    dgChannel.close();
}

2. UseDGWithIPv6#main()

Project: jdk7u-jdk
File: UseDGWithIPv6.java
public static void main(String[] args) throws IOException {
    ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
    DatagramChannel dgChannel = DatagramChannel.open();
    for (int i = 0; i < targets.length; i++) {
        data.rewind();
        SocketAddress sa = new InetSocketAddress(targets[i], port);
        System.out.println("-------------\nDG_Sending data:" + "\n    remaining:" + data.remaining() + "\n     position:" + data.position() + "\n        limit:" + data.limit() + "\n     capacity:" + data.capacity() + " bytes on DG channel to " + sa);
        try {
            int n = dgChannel.send(data, sa);
            System.out.println("DG_Sent " + n + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    dgChannel.close();
}

3. DatagramChannelTest#test_bind_any()

Project: j2objc
File: DatagramChannelTest.java
private void test_bind_any(InetAddress bindAddress) throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    dc.socket().bind(new InetSocketAddress(bindAddress, 0));
    assertTrue(dc.isOpen());
    assertFalse(dc.isConnected());
    InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
    assertTrue(actualAddress.getAddress().isAnyLocalAddress());
    assertTrue(actualAddress.getPort() > 0);
    dc.close();
}

4. DatagramChannelTest#test_bind_unresolvedAddress()

Project: j2objc
File: DatagramChannelTest.java
public void test_bind_unresolvedAddress() throws IOException {
    DatagramChannel dc = DatagramChannel.open();
    try {
        dc.socket().bind(new InetSocketAddress("unresolvedname", 31415));
        fail();
    } catch (IOException expected) {
    }
    assertTrue(dc.isOpen());
    assertFalse(dc.isConnected());
    dc.close();
}

5. DatagramChannelTest#test_read_intoReadOnlyByteArrays()

Project: j2objc
File: DatagramChannelTest.java
public void test_read_intoReadOnlyByteArrays() throws Exception {
    ByteBuffer readOnly = ByteBuffer.allocate(1).asReadOnlyBuffer();
    DatagramSocket ds = new DatagramSocket(0);
    DatagramChannel dc = DatagramChannel.open();
    dc.connect(ds.getLocalSocketAddress());
    try {
        dc.read(readOnly);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        dc.read(new ByteBuffer[] { readOnly });
        fail();
    } catch (IllegalArgumentException expected) {
    }
    try {
        dc.read(new ByteBuffer[] { readOnly }, 0, 1);
        fail();
    } catch (IllegalArgumentException expected) {
    }
}

6. IODispatcher#addEndpoint()

Project: axis2-transports
File: 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.
     * 
     * @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());
}

7. IODispatcher#addEndpoint()

Project: axis2-java
File: 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.
     * 
     * @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());
}

8. ExportBenchmark#setupSocketListener()

Project: voltdb
File: ExportBenchmark.java
/**
     * Sets up a UDP socket on a certain port to listen for connections.
     */
private void setupSocketListener() {
    DatagramChannel channel = null;
    // Setup Listener
    try {
        statsSocketSelector = SelectorProvider.provider().openSelector();
        channel = DatagramChannel.open();
        channel.configureBlocking(false);
    } catch (IOException e) {
        exitWithException("Couldn't set up network channels", e);
    }
    // Bind to port & register with a channel
    try {
        InetSocketAddress isa = new InetSocketAddress(CoreUtils.getLocalAddress(), config.statsPort);
        channel.socket().setReuseAddress(true);
        channel.socket().bind(isa);
        channel.register(statsSocketSelector, SelectionKey.OP_READ);
    } catch (IOException e) {
        exitWithException("Couldn't bind to socket", e);
    }
}

9. AsyncServer#connectDatagram()

Project: RemoteDroid
File: AsyncServer.java
public AsyncDatagramSocket connectDatagram(final SocketAddress remote) throws IOException {
    final DatagramChannel socket = DatagramChannel.open();
    final AsyncDatagramSocket handler = new AsyncDatagramSocket();
    handler.attach(socket);
    // ugh.. this should really be post to make it nonblocking...
    // but i want datagrams to be immediately writable.
    // they're not really used anyways.
    run(new Runnable() {

        @Override
        public void run() {
            try {
                handleSocket(handler);
                socket.connect(remote);
            } catch (IOException e) {
                StreamUtility.closeQuietly(socket);
            }
        }
    });
    return handler;
}

10. AsyncServer#openDatagram()

Project: RemoteDroid
File: AsyncServer.java
public AsyncDatagramSocket openDatagram(final SocketAddress address, final boolean reuseAddress) throws IOException {
    final DatagramChannel socket = DatagramChannel.open();
    final AsyncDatagramSocket handler = new AsyncDatagramSocket();
    handler.attach(socket);
    // ugh.. this should really be post to make it nonblocking...
    // but i want datagrams to be immediately writable.
    // they're not really used anyways.
    run(new Runnable() {

        @Override
        public void run() {
            try {
                if (reuseAddress)
                    socket.socket().setReuseAddress(reuseAddress);
                socket.socket().bind(address);
                handleSocket(handler);
            } catch (IOException e) {
                Log.e(LOGTAG, "Datagram error", e);
                StreamUtility.closeQuietly(socket);
            }
        }
    });
    return handler;
}

11. AsyncServer#connectDatagram()

Project: RemoteDroid
File: AsyncServer.java
public AsyncDatagramSocket connectDatagram(final String host, final int port) throws IOException {
    final DatagramChannel socket = DatagramChannel.open();
    final AsyncDatagramSocket handler = new AsyncDatagramSocket();
    handler.attach(socket);
    // ugh.. this should really be post to make it nonblocking...
    // but i want datagrams to be immediately writable.
    // they're not really used anyways.
    run(new Runnable() {

        @Override
        public void run() {
            try {
                final SocketAddress remote = new InetSocketAddress(host, port);
                handleSocket(handler);
                socket.connect(remote);
            } catch (IOException e) {
                Log.e(LOGTAG, "Datagram error", e);
                StreamUtility.closeQuietly(socket);
            }
        }
    });
    return handler;
}

12. UdpConnection#send()

Project: kryonet
File: UdpConnection.java
/** This method is thread safe. */
public int send(Connection connection, Object object, SocketAddress address) throws IOException {
    DatagramChannel datagramChannel = this.datagramChannel;
    if (datagramChannel == null)
        throw new SocketException("Connection is closed.");
    synchronized (writeLock) {
        try {
            try {
                serialization.write(connection, writeBuffer, object);
            } catch (Exception ex) {
                throw new KryoNetException("Error serializing object of type: " + object.getClass().getName(), ex);
            }
            writeBuffer.flip();
            int length = writeBuffer.limit();
            datagramChannel.send(writeBuffer, address);
            lastCommunicationTime = System.currentTimeMillis();
            boolean wasFullWrite = !writeBuffer.hasRemaining();
            return wasFullWrite ? length : -1;
        } finally {
            writeBuffer.clear();
        }
    }
}

13. DatagramChannelTest#testInitialState()

Project: j2objc
File: DatagramChannelTest.java
public void testInitialState() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    try {
        DatagramSocket socket = dc.socket();
        assertFalse(socket.isBound());
        assertFalse(socket.getBroadcast());
        assertFalse(socket.isClosed());
        assertFalse(socket.isConnected());
        assertEquals(0, socket.getLocalPort());
        assertTrue(socket.getLocalAddress().isAnyLocalAddress());
        assertNull(socket.getLocalSocketAddress());
        assertNull(socket.getInetAddress());
        assertEquals(-1, socket.getPort());
        assertNull(socket.getRemoteSocketAddress());
        assertFalse(socket.getReuseAddress());
        assertSame(dc, socket.getChannel());
    } finally {
        dc.close();
    }
}

14. UDPClient#recv()

Project: browsermob-proxy
File: UDPClient.java
byte[] recv(int max) throws IOException {
    DatagramChannel channel = (DatagramChannel) key.channel();
    byte[] temp = new byte[max];
    key.interestOps(SelectionKey.OP_READ);
    try {
        while (!key.isReadable()) blockUntil(key, endTime);
    } finally {
        if (key.isValid())
            key.interestOps(0);
    }
    long ret = channel.read(ByteBuffer.wrap(temp));
    if (ret <= 0)
        throw new EOFException();
    int len = (int) ret;
    byte[] data = new byte[len];
    System.arraycopy(temp, 0, data, 0, len);
    verboseLog("UDP read", data);
    return data;
}

15. UDPClient#bind_random()

Project: browsermob-proxy
File: UDPClient.java
private void bind_random(InetSocketAddress addr) throws IOException {
    DatagramChannel channel = (DatagramChannel) key.channel();
    InetSocketAddress temp;
    for (int i = 0; i < 1024; i++) {
        try {
            int port = prng.nextInt(EPHEMERAL_RANGE) + EPHEMERAL_START;
            if (addr != null)
                temp = new InetSocketAddress(addr.getAddress(), port);
            else
                temp = new InetSocketAddress(port);
            channel.socket().bind(temp);
            bound = true;
            return;
        } catch (SocketException e) {
        }
    }
}

16. SendHackSelectReceiveUdpPing#run()

Project: Aeron
File: SendHackSelectReceiveUdpPing.java
private void run() throws IOException {
    receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    receiveChannel.register(selector, OP_READ, this);
    final NioSelectedKeySet keySet = Common.keySet(selector);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(HISTOGRAM, SEND_ADDRESS, buffer, sendChannel, selector, keySet, running);
        HISTOGRAM.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}

17. TransferToPong#main()

Project: Aeron
File: TransferToPong.java
public static void main(final String[] args) throws IOException {
    final FileChannel receiveFileChannel = Common.createTmpFileChannel();
    final ByteBuffer receiveByteBuffer = receiveFileChannel.map(READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveDatagramChannel = DatagramChannel.open();
    Common.init(receiveDatagramChannel);
    receiveDatagramChannel.bind(new InetSocketAddress(LOCALHOST, 40124));
    receiveDatagramChannel.connect(new InetSocketAddress(LOCALHOST, 40123));
    final FileChannel sendFileChannel = Common.createTmpFileChannel();
    final ByteBuffer sendByteBuffer = sendFileChannel.map(READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel sendDatagramChannel = DatagramChannel.open();
    Common.init(sendDatagramChannel);
    sendDatagramChannel.bind(new InetSocketAddress(LOCALHOST, 40125));
    sendDatagramChannel.connect(new InetSocketAddress(LOCALHOST, 40126));
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    final int packetSize = SIZE_OF_LONG * 2;
    while (true) {
        boolean available = false;
        while (!available) {
            if (!running.get()) {
                return;
            }
            final long bytesReceived = receiveFileChannel.transferFrom(receiveDatagramChannel, 0, packetSize);
            if (packetSize == bytesReceived) {
                available = true;
            }
        }
        final long receivedSequenceNumber = receiveByteBuffer.getLong(0);
        final long receivedTimestamp = receiveByteBuffer.getLong(SIZE_OF_LONG);
        sendByteBuffer.putLong(0, receivedSequenceNumber);
        sendByteBuffer.putLong(SIZE_OF_LONG, receivedTimestamp);
        final long bytesSent = sendFileChannel.transferTo(0, packetSize, sendDatagramChannel);
        if (packetSize != bytesSent) {
            throw new IllegalStateException("Invalid bytes sent " + bytesSent);
        }
    }
}

18. TransferToPing#main()

Project: Aeron
File: TransferToPing.java
public static void main(final String[] args) throws IOException {
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final FileChannel sendFileChannel = Common.createTmpFileChannel();
    final ByteBuffer sendByteBuffer = sendFileChannel.map(READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel sendDatagramChannel = DatagramChannel.open();
    init(sendDatagramChannel);
    sendDatagramChannel.bind(new InetSocketAddress(LOCALHOST, 40123));
    sendDatagramChannel.connect(new InetSocketAddress(LOCALHOST, 40124));
    final FileChannel receiveFileChannel = Common.createTmpFileChannel();
    final ByteBuffer receiveByteBuffer = receiveFileChannel.map(READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveDatagramChannel = DatagramChannel.open();
    init(receiveDatagramChannel);
    receiveDatagramChannel.bind(new InetSocketAddress(LOCALHOST, 40126));
    receiveDatagramChannel.connect(new InetSocketAddress(LOCALHOST, 40125));
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, receiveFileChannel, receiveDatagramChannel, receiveByteBuffer, sendFileChannel, sendDatagramChannel, sendByteBuffer, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}

19. SendSelectReceiveUdpPing#run()

Project: Aeron
File: SendSelectReceiveUdpPing.java
private void run() throws IOException {
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final IntSupplier handler = () -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long timestamp = buffer.getLong(SIZE_OF_LONG);
            if (receivedSequenceNumber != sequenceNumber) {
                throw new IllegalStateException("Data Loss:" + sequenceNumber + " to " + receivedSequenceNumber);
            }
            final long duration = System.nanoTime() - timestamp;
            histogram.recordValue(duration);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, handler);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, SEND_ADDRESS, buffer, sendChannel, selector, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}

20. SelectReceiveSendUdpPong#run()

Project: Aeron
File: SelectReceiveSendUdpPong.java
private void run() throws IOException {
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final IntSupplier handler = () -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
            buffer.clear();
            buffer.putLong(receivedSequenceNumber);
            buffer.putLong(receivedTimestamp);
            buffer.flip();
            sendChannel.send(buffer, sendAddress);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, handler);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (true) {
        while (selector.selectNow() == 0) {
            if (!running.get()) {
                return;
            }
        }
        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext()) {
            final SelectionKey key = iter.next();
            if (key.isReadable()) {
                ((IntSupplier) key.attachment()).getAsInt();
            }
            iter.remove();
        }
    }
}

21. HackSelectReceiveSendUdpPong#run()

Project: Aeron
File: HackSelectReceiveSendUdpPong.java
private void run() throws IOException {
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final Selector selector = Selector.open();
    final NioSelectedKeySet keySet = Common.keySet(selector);
    final ToIntFunction<SelectionKey> handler = ( key) -> {
        try {
            buffer.clear();
            receiveChannel.receive(buffer);
            final long receivedSequenceNumber = buffer.getLong(0);
            final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
            buffer.clear();
            buffer.putLong(receivedSequenceNumber);
            buffer.putLong(receivedTimestamp);
            buffer.flip();
            sendChannel.send(buffer, sendAddress);
        } catch (final IOException ex) {
            ex.printStackTrace();
        }
        return 1;
    };
    receiveChannel.register(selector, OP_READ, null);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (true) {
        while (selector.selectNow() == 0) {
            if (!running.get()) {
                return;
            }
        }
        keySet.forEach(handler);
    }
}

22. GelfUDPSender#initiateChannel()

Project: gelfj
File: GelfUDPSender.java
private DatagramChannel initiateChannel() throws IOException {
    DatagramChannel resultingChannel = DatagramChannel.open();
    resultingChannel.socket().bind(new InetSocketAddress(0));
    resultingChannel.connect(new InetSocketAddress(this.host, this.port));
    resultingChannel.configureBlocking(false);
    return resultingChannel;
}

23. OortMulticastConfigurer#doStart()

Project: cometd
File: OortMulticastConfigurer.java
@Override
protected void doStart() throws Exception {
    // Bind sender to an ephemeral port and set the TTL
    DatagramChannel sender = DatagramChannel.open();
    sender.setOption(StandardSocketOptions.IP_MULTICAST_TTL, getTimeToLive());
    if (groupAddress == null)
        groupAddress = InetAddress.getByName("239.255.0.1");
    ProtocolFamily protocolFamily = StandardProtocolFamily.INET;
    if (groupAddress instanceof Inet6Address)
        protocolFamily = StandardProtocolFamily.INET6;
    // Bind receiver to the given port and bind address
    InetAddress bindTo = getBindAddress();
    InetSocketAddress bindSocketAddress = bindTo == null ? new InetSocketAddress(groupPort) : new InetSocketAddress(bindTo, groupPort);
    DatagramChannel receiver = DatagramChannel.open(protocolFamily).setOption(StandardSocketOptions.SO_REUSEADDR, true).bind(bindSocketAddress);
    if (logger.isDebugEnabled())
        logger.debug("Bound multicast receiver to {} with protocol family {}", bindSocketAddress, protocolFamily);
    List<NetworkInterface> groupInterfaces = getGroupInterfaces();
    if (groupInterfaces == null)
        groupInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    boolean joined = false;
    for (NetworkInterface groupInterface : groupInterfaces) {
        if (logger.isDebugEnabled())
            logger.debug("Joining multicast group with {}", groupInterface);
        if (groupInterface.isLoopback() || groupInterface.isPointToPoint() || !groupInterface.supportsMulticast() || !groupInterface.getInetAddresses().hasMoreElements()) {
            if (logger.isDebugEnabled())
                logger.debug("Skipped joining multicast group with {}", groupInterface);
            continue;
        }
        try {
            receiver.join(groupAddress, groupInterface);
            if (logger.isDebugEnabled())
                logger.debug("Joined multicast group with {}", groupInterface);
            joined = true;
        } catch (Exception x) {
            if (logger.isDebugEnabled())
                logger.debug("Exception joining multicast group with " + groupInterface, x);
        }
    }
    if (!joined)
        throw new IOException("Could not join multicast group with " + groupInterfaces);
    active = true;
    senderThread = new Thread(new MulticastSender(sender), "Oort-Multicast-Sender-" + ids.incrementAndGet());
    senderThread.setDaemon(true);
    senderThread.start();
    receiverThread = new Thread(new MulticastReceiver(receiver), "Oort-Multicast-Receiver-" + ids.incrementAndGet());
    receiverThread.setDaemon(true);
    receiverThread.start();
}

24. EmptyBuffer#test()

Project: openjdk
File: EmptyBuffer.java
private static void test() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    InetAddress localHost = InetAddress.getLocalHost();
    dc.bind(new InetSocketAddress(localHost, 0));
    Server server = new Server(dc.getLocalAddress());
    Thread serverThread = new Thread(server);
    serverThread.start();
    try {
        InetSocketAddress isa = new InetSocketAddress(localHost, server.port());
        dc.connect(isa);
        ByteBuffer bb = ByteBuffer.allocateDirect(12);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(1).putLong(1);
        bb.flip();
        dc.write(bb);
        bb.rewind();
        dc.write(bb);
        bb.rewind();
        dc.write(bb);
        Thread.sleep(2000);
        serverThread.interrupt();
        server.throwException();
    } finally {
        dc.close();
    }
}

25. DatagramChannelAllocator#allocate()

Project: jmxtrans
File: DatagramChannelAllocator.java
@Override
public DatagramChannelPoolable allocate(Slot slot) throws Exception {
    DatagramChannel channel = DatagramChannel.open();
    channel.connect(new InetSocketAddress(server.getHostName(), server.getPort()));
    ChannelWriter writer = new ChannelWriter(bufferSize, charset, channel);
    return new DatagramChannelPoolable(slot, writer, channel, flushStrategy);
}

26. DatagramChannelTest#test_bind()

Project: j2objc
File: DatagramChannelTest.java
private void test_bind(InetAddress bindAddress) throws IOException {
    DatagramChannel dc = DatagramChannel.open();
    dc.socket().bind(new InetSocketAddress(bindAddress, 0));
    InetSocketAddress actualAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
    assertEquals(bindAddress, actualAddress.getAddress());
    assertTrue(actualAddress.getPort() > 0);
    dc.close();
}

27. UDPClient#send()

Project: browsermob-proxy
File: UDPClient.java
void send(byte[] data) throws IOException {
    DatagramChannel channel = (DatagramChannel) key.channel();
    verboseLog("UDP write", data);
    channel.write(ByteBuffer.wrap(data));
}

28. UDPClient#connect()

Project: browsermob-proxy
File: UDPClient.java
void connect(SocketAddress addr) throws IOException {
    if (!bound)
        bind(null);
    DatagramChannel channel = (DatagramChannel) key.channel();
    channel.connect(addr);
}

29. WriteReceiveUdpPing#main()

Project: Aeron
File: WriteReceiveUdpPing.java
public static void main(final String[] args) throws IOException {
    int numChannels = 1;
    if (1 == args.length) {
        numChannels = Integer.parseInt(args[0]);
    }
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(MTU_LENGTH_DEFAULT);
    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++) {
        receiveChannels[i] = DatagramChannel.open();
        init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", PONG_PORT + i));
    }
    final InetSocketAddress writeAddress = new InetSocketAddress("localhost", PING_PORT);
    final DatagramChannel writeChannel = DatagramChannel.open();
    init(writeChannel, writeAddress);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, buffer, receiveChannels, writeChannel, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000_000_000);
    }
}

30. SendReceiveUdpPing#main()

Project: Aeron
File: SendReceiveUdpPing.java
public static void main(final String[] args) throws IOException {
    int numChannels = 1;
    if (1 == args.length) {
        numChannels = Integer.parseInt(args[0]);
    }
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++) {
        receiveChannels[i] = DatagramChannel.open();
        init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PONG_PORT + i));
    }
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PING_PORT);
    final DatagramChannel sendChannel = DatagramChannel.open();
    init(sendChannel);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (running.get()) {
        measureRoundTrip(histogram, sendAddress, buffer, receiveChannels, sendChannel, running);
        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000_000_000);
    }
}

31. ReceiveWriteUdpPong#main()

Project: Aeron
File: ReceiveWriteUdpPong.java
public static void main(final String[] args) throws IOException {
    int numChannels = 1;
    if (1 == args.length) {
        numChannels = Integer.parseInt(args[0]);
    }
    final ByteBuffer buffer = ByteBuffer.allocateDirect(MTU_LENGTH_DEFAULT);
    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++) {
        receiveChannels[i] = DatagramChannel.open();
        Common.init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PING_PORT + i));
    }
    final InetSocketAddress writeAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final DatagramChannel writeChannel = DatagramChannel.open();
    Common.init(writeChannel, writeAddress);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (true) {
        buffer.clear();
        boolean available = false;
        while (!available) {
            if (!running.get()) {
                return;
            }
            for (int i = receiveChannels.length - 1; i >= 0; i--) {
                if (null != receiveChannels[i].receive(buffer)) {
                    available = true;
                    break;
                }
            }
        }
        final long receivedSequenceNumber = buffer.getLong(0);
        final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
        buffer.clear();
        buffer.putLong(receivedSequenceNumber);
        buffer.putLong(receivedTimestamp);
        buffer.flip();
        writeChannel.write(buffer);
    }
}

32. ReceiveSendUdpPong#main()

Project: Aeron
File: ReceiveSendUdpPong.java
public static void main(final String[] args) throws IOException {
    int numChannels = 1;
    if (1 == args.length) {
        numChannels = Integer.parseInt(args[0]);
    }
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);
    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++) {
        receiveChannels[i] = DatagramChannel.open();
        init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PING_PORT + i));
    }
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    while (true) {
        buffer.clear();
        boolean available = false;
        while (!available) {
            if (!running.get()) {
                return;
            }
            for (int i = receiveChannels.length - 1; i >= 0; i--) {
                if (null != receiveChannels[i].receive(buffer)) {
                    available = true;
                    break;
                }
            }
        }
        final long receivedSequenceNumber = buffer.getLong(0);
        final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);
        buffer.clear();
        buffer.putLong(receivedSequenceNumber);
        buffer.putLong(receivedTimestamp);
        buffer.flip();
        sendChannel.send(buffer, sendAddress);
    }
}

33. SpanStreamUdpSender#createChannel()

Project: pinpoint
File: SpanStreamUdpSender.java
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) {
    DatagramChannel datagramChannel = null;
    DatagramSocket socket = null;
    try {
        datagramChannel = DatagramChannel.open();
        socket = datagramChannel.socket();
        socket.setSoTimeout(timeout);
        socket.setSendBufferSize(sendBufferSize);
        if (logger.isWarnEnabled()) {
            final int checkSendBufferSize = socket.getSendBufferSize();
            if (sendBufferSize != checkSendBufferSize) {
                logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize);
            }
        }
        InetSocketAddress serverAddress = new InetSocketAddress(host, port);
        datagramChannel.connect(serverAddress);
        return datagramChannel;
    } catch (IOException e) {
        if (socket != null) {
            socket.close();
        }
        if (datagramChannel != null) {
            try {
                datagramChannel.close();
            } catch (IOException ignored) {
            }
        }
        throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e);
    }
}

34. NioUDPDataSender#createChannel()

Project: pinpoint
File: NioUDPDataSender.java
private DatagramChannel createChannel(String host, int port, int timeout, int sendBufferSize) {
    DatagramChannel datagramChannel = null;
    DatagramSocket socket = null;
    try {
        datagramChannel = DatagramChannel.open();
        socket = datagramChannel.socket();
        socket.setSoTimeout(timeout);
        socket.setSendBufferSize(sendBufferSize);
        if (logger.isWarnEnabled()) {
            final int checkSendBufferSize = socket.getSendBufferSize();
            if (sendBufferSize != checkSendBufferSize) {
                logger.warn("DatagramChannel.setSendBufferSize() error. {}!={}", sendBufferSize, checkSendBufferSize);
            }
        }
        InetSocketAddress serverAddress = new InetSocketAddress(host, port);
        datagramChannel.connect(serverAddress);
        return datagramChannel;
    } catch (IOException e) {
        if (socket != null) {
            socket.close();
        }
        if (datagramChannel != null) {
            try {
                datagramChannel.close();
            } catch (IOException ignored) {
            }
        }
        throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e);
    }
}

35. NotBound#main()

Project: openjdk
File: NotBound.java
public static void main(String[] args) throws IOException {
    DatagramChannel dc;
    // connect
    dc = DatagramChannel.open();
    try {
        DatagramChannel peer = DatagramChannel.open().bind(new InetSocketAddress(0));
        int peerPort = ((InetSocketAddress) (peer.getLocalAddress())).getPort();
        try {
            dc.connect(new InetSocketAddress(InetAddress.getLocalHost(), peerPort));
            checkBound(dc);
        } finally {
            peer.close();
        }
    } finally {
        dc.close();
    }
    // send
    dc = DatagramChannel.open();
    try {
        ByteBuffer bb = ByteBuffer.wrap("ignore this".getBytes());
        SocketAddress target = new InetSocketAddress(InetAddress.getLocalHost(), 5000);
        dc.send(bb, target);
        checkBound(dc);
    } finally {
        dc.close();
    }
    // receive (blocking)
    dc = DatagramChannel.open();
    try {
        ByteBuffer bb = ByteBuffer.allocateDirect(128);
        wakeupWhenBound(dc);
        SocketAddress sender = dc.receive(bb);
        if (sender == null)
            throw new RuntimeException("Sender should not be null");
        checkBound(dc);
    } finally {
        dc.close();
    }
    // receive (non-blocking)
    dc = DatagramChannel.open();
    try {
        dc.configureBlocking(false);
        ByteBuffer bb = ByteBuffer.allocateDirect(128);
        SocketAddress sender = dc.receive(bb);
        if (sender != null)
            throw new RuntimeException("Sender should be null");
        checkBound(dc);
    } finally {
        dc.close();
    }
}

36. ChangingAddress#main()

Project: openjdk
File: ChangingAddress.java
public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    SocketAddress remote = new InetSocketAddress(lh, 1234);
    DatagramSocket ds = null;
    DatagramChannel dc = null;
    try {
        ds = new DatagramSocket();
        dc = DatagramChannel.open().bind(new InetSocketAddress(0));
        check(ds, dc);
        ds.connect(remote);
        dc.connect(remote);
        check(ds, dc);
        ds.disconnect();
        dc.disconnect();
        check(ds, dc);
        // repeat tests using socket adapter
        ds.connect(remote);
        dc.socket().connect(remote);
        check(ds, dc);
        ds.disconnect();
        dc.socket().disconnect();
        check(ds, dc);
    } finally {
        if (ds != null)
            ds.close();
        if (dc != null)
            dc.close();
    }
}

37. NioDatagramChannel#doReadMessages()

Project: netty
File: NioDatagramChannel.java
@Override
protected int doReadMessages(List<Object> buf) throws Exception {
    DatagramChannel ch = javaChannel();
    DatagramChannelConfig config = config();
    RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle();
    ByteBuf data = allocHandle.allocate(config.getAllocator());
    allocHandle.attemptedBytesRead(data.writableBytes());
    boolean free = true;
    try {
        ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes());
        int pos = nioData.position();
        InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData);
        if (remoteAddress == null) {
            return 0;
        }
        allocHandle.lastBytesRead(nioData.position() - pos);
        buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()), localAddress(), remoteAddress));
        free = false;
        return 1;
    } catch (Throwable cause) {
        PlatformDependent.throwException(cause);
        return -1;
    } finally {
        if (free) {
            data.release();
        }
    }
}

38. NioDatagramChannel#isActive()

Project: netty
File: NioDatagramChannel.java
@Override
@SuppressWarnings("deprecation")
public boolean isActive() {
    DatagramChannel ch = javaChannel();
    return ch.isOpen() && (config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered() || ch.socket().isBound());
}

39. NioUdpClient#connect()

Project: mina
File: NioUdpClient.java
/**
     * {@inheritDoc}
     */
@Override
public IoFuture<IoSession> connect(SocketAddress remoteAddress) {
    Assert.assertNotNull(remoteAddress, "remoteAddress");
    DatagramChannel ch;
    try {
        ch = DatagramChannel.open();
    } catch (IOException e) {
        throw new MinaRuntimeException("can't create a new socket, out of file descriptors ?", e);
    }
    try {
        ch.configureBlocking(false);
    } catch (IOException e) {
        throw new MinaRuntimeException("can't configure socket as non-blocking", e);
    }
    UdpSessionConfig config = getSessionConfig();
    NioSelectorLoop loop = (NioSelectorLoop) readWriteSelectorPool.getSelectorLoop();
    NioUdpSession session = new NioUdpSession(this, idleChecker, ch, null, remoteAddress, loop);
    session.setConnected();
    // apply idle configuration
    session.getConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, config.getIdleTimeInMillis(IdleStatus.READ_IDLE));
    session.getConfig().setIdleTimeInMillis(IdleStatus.WRITE_IDLE, config.getIdleTimeInMillis(IdleStatus.WRITE_IDLE));
    // Manage the Idle status
    idleChecker.sessionRead(session, System.currentTimeMillis());
    idleChecker.sessionWritten(session, System.currentTimeMillis());
    // apply the default service socket configuration
    Boolean reuseAddress = config.isReuseAddress();
    if (reuseAddress != null) {
        session.getConfig().setReuseAddress(reuseAddress);
    }
    Integer readBufferSize = config.getReadBufferSize();
    if (readBufferSize != null) {
        session.getConfig().setReadBufferSize(readBufferSize);
    } else {
        int rcvBufferSize;
        try {
            rcvBufferSize = ch.socket().getReceiveBufferSize();
            session.getConfig().setReadBufferSize(rcvBufferSize);
        } catch (SocketException e) {
            throw new MinaRuntimeException("can't configure socket receive buffer size", e);
        }
    }
    Integer sendBufferSize = config.getSendBufferSize();
    if (sendBufferSize != null) {
        session.getConfig().setSendBufferSize(sendBufferSize);
    } else {
        int sndBufferSize;
        try {
            sndBufferSize = ch.socket().getSendBufferSize();
            session.getConfig().setSendBufferSize(sndBufferSize);
        } catch (SocketException e) {
            throw new MinaRuntimeException("can't configure socket send buffe size", e);
        }
    }
    Integer trafficClass = config.getTrafficClass();
    if (trafficClass != null) {
        session.getConfig().setTrafficClass(trafficClass);
    }
    loop.register(false, false, true, false, session, ch, null);
    ConnectFuture cf = new ConnectFuture();
    cf.complete(session);
    return cf;
}

40. UDPInlinerSender#doSend()

Project: metrics-influxdb
File: UDPInlinerSender.java
@Override
protected boolean doSend(Collection<Measure> measures) {
    if (measures.isEmpty()) {
        return true;
    }
    DatagramChannel channel = null;
    try {
        channel = DatagramChannel.open();
    } catch (IOException e) {
        LOGGER.error("failed open udp channel", e);
        return false;
    }
    Iterator<Measure> measuresIterator = measures.iterator();
    int errorCounter = 0;
    int successCounter = 0;
    while (measuresIterator.hasNext()) {
        String measuresAsString = inliner.inline(measuresIterator.next());
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Measure being sent:\n{}", measuresAsString);
            }
            ByteBuffer buffer = ByteBuffer.wrap(measuresAsString.getBytes(Miscellaneous.UTF8));
            channel.send(buffer, serverAddress);
            successCounter++;
        } catch (Throwable e) {
            errorCounter++;
        }
    }
    LOGGER.debug("{} Measures sent to UDP[{}:{}]; successes: {}, failures: {}", measures.size(), serverAddress.getHostString(), serverAddress.getPort(), successCounter, errorCounter);
    try {
        channel.close();
    } catch (IOException e) {
        LOGGER.error("failed close udp channel", e);
    }
    return successCounter > 0;
}

41. InfluxdbUdp#sendRequest()

Project: metrics-influxdb
File: InfluxdbUdp.java
@Override
public int sendRequest(boolean throwExc, boolean printJson) throws Exception {
    DatagramChannel channel = null;
    try {
        channel = DatagramChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress(host, port);
        for (JsonBuilder builder : jsonBuilders) {
            String json = builder.toJsonString();
            if (printJson || debugJson) {
                System.out.println(json);
            }
            ByteBuffer buffer = ByteBuffer.wrap(json.getBytes());
            channel.send(buffer, socketAddress);
            buffer.clear();
        }
    } catch (Exception e) {
        if (throwExc) {
            throw e;
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
    }
    return 0;
}

42. UdpConnection#readFromAddress()

Project: kryonet
File: UdpConnection.java
public InetSocketAddress readFromAddress() throws IOException {
    DatagramChannel datagramChannel = this.datagramChannel;
    if (datagramChannel == null)
        throw new SocketException("Connection is closed.");
    lastCommunicationTime = System.currentTimeMillis();
    return (InetSocketAddress) datagramChannel.receive(readBuffer);
}

43. DatagramChannelExpiration#hasExpired()

Project: jmxtrans
File: DatagramChannelExpiration.java
@Override
public boolean hasExpired(SlotInfo<? extends DatagramChannelPoolable> info) throws Exception {
    DatagramChannel channel = info.getPoolable().getChannel();
    return !channel.isConnected() || !channel.isOpen();
}

44. mcast#start()

Project: JGroups
File: mcast.java
protected void start() throws Exception {
    Receiver r = null;
    DatagramChannel channel = null;
    try {
        r = new Receiver();
        r.start();
        channel = DatagramChannel.open(prot_family).setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl).bind(new InetSocketAddress(bind_addr, local_port));
        sock = channel.socket();
    } catch (Exception ex) {
        if (channel != null)
            channel.close();
        if (r != null) {
            r.kill();
            r.interrupt();
        }
        throw ex;
    }
    DataInputStream in = new DataInputStream(System.in);
    while (true) {
        System.out.print("> ");
        try {
            String line = Util.readLine(in);
            byte[] buf = line.getBytes();
            DatagramPacket packet = new DatagramPacket(buf, buf.length, mcast_addr, mcast_port);
            sock.send(packet);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

45. NotBound#main()

Project: jdk7u-jdk
File: NotBound.java
public static void main(String[] args) throws IOException {
    DatagramChannel dc;
    // connect
    dc = DatagramChannel.open();
    try {
        DatagramChannel peer = DatagramChannel.open().bind(new InetSocketAddress(0));
        int peerPort = ((InetSocketAddress) (peer.getLocalAddress())).getPort();
        try {
            dc.connect(new InetSocketAddress(InetAddress.getLocalHost(), peerPort));
            checkBound(dc);
        } finally {
            peer.close();
        }
    } finally {
        dc.close();
    }
    // send
    dc = DatagramChannel.open();
    try {
        ByteBuffer bb = ByteBuffer.wrap("ignore this".getBytes());
        SocketAddress target = new InetSocketAddress(InetAddress.getLocalHost(), 5000);
        dc.send(bb, target);
        checkBound(dc);
    } finally {
        dc.close();
    }
    // receive (blocking)
    dc = DatagramChannel.open();
    try {
        ByteBuffer bb = ByteBuffer.allocateDirect(128);
        wakeupWhenBound(dc);
        SocketAddress sender = dc.receive(bb);
        if (sender == null)
            throw new RuntimeException("Sender should not be null");
        checkBound(dc);
    } finally {
        dc.close();
    }
    // receive (non-blocking)
    dc = DatagramChannel.open();
    try {
        dc.configureBlocking(false);
        ByteBuffer bb = ByteBuffer.allocateDirect(128);
        SocketAddress sender = dc.receive(bb);
        if (sender != null)
            throw new RuntimeException("Sender should be null");
        checkBound(dc);
    } finally {
        dc.close();
    }
}

46. ChangingAddress#main()

Project: jdk7u-jdk
File: ChangingAddress.java
public static void main(String[] args) throws Exception {
    InetAddress lh = InetAddress.getLocalHost();
    SocketAddress remote = new InetSocketAddress(lh, 1234);
    DatagramSocket ds = null;
    DatagramChannel dc = null;
    try {
        ds = new DatagramSocket();
        dc = DatagramChannel.open().bind(new InetSocketAddress(0));
        check(ds, dc);
        ds.connect(remote);
        dc.connect(remote);
        check(ds, dc);
        ds.disconnect();
        dc.disconnect();
        check(ds, dc);
        // repeat tests using socket adapter
        ds.connect(remote);
        dc.socket().connect(remote);
        check(ds, dc);
        ds.disconnect();
        dc.socket().disconnect();
        check(ds, dc);
    } finally {
        if (ds != null)
            ds.close();
        if (dc != null)
            dc.close();
    }
}

47. DatagramChannelTest#testNonBlockingRecv()

Project: j2objc
File: DatagramChannelTest.java
// http://code.google.com/p/android/issues/detail?id=16579
public void testNonBlockingRecv() throws Exception {
    DatagramChannel dc = DatagramChannel.open();
    try {
        dc.configureBlocking(false);
        dc.socket().bind(null);
        // Should return immediately, since we're non-blocking.
        assertNull(dc.receive(ByteBuffer.allocate(2048)));
    } finally {
        dc.close();
    }
}

48. UDPReceiverThread#run()

Project: h2o-3
File: UDPReceiverThread.java
// ---
// Started by main() on a single thread, this code manages reading UDP packets
@SuppressWarnings("resource")
public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1);
    DatagramChannel sock = datagramChannel, errsock = null;
    boolean saw_error = false;
    while (true) {
        try {
            // Cleanup from any prior socket failures.  Rare unless we're really sick.
            if (errsock != null) {
                // One time attempt a socket close
                final DatagramChannel tmp2 = errsock;
                errsock = null;
                // Could throw, but errsock cleared for next pass
                tmp2.close();
            }
            // prevent deny-of-service endless socket-creates
            if (saw_error)
                Thread.sleep(1000);
            saw_error = false;
            // Common-case setup of a socket
            if (sock == null) {
                sock = DatagramChannel.open();
                sock.socket().bind(H2O.SELF._key);
            }
            // Receive a packet & handle it
            basic_packet_handling(new AutoBuffer(sock));
        } catch (java.nio.channels.AsynchronousCloseException ex) {
            break;
        } catch (java.nio.channels.ClosedChannelException ex) {
            break;
        } catch (Exception e) {
            Log.err("UDP Receiver error on port " + H2O.H2O_PORT, e);
            saw_error = true;
            errsock = sock;
            sock = null;
        }
    }
}

49. UDPReceiverThread#run()

Project: h2o-2
File: UDPReceiverThread.java
// ---
// Started by main() on a single thread, this code manages reading UDP packets
@SuppressWarnings("resource")
public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1);
    DatagramChannel sock = H2O._udpSocket, errsock = null;
    boolean saw_error = false;
    while (true) {
        try {
            // Cleanup from any prior socket failures.  Rare unless we're really sick.
            if (errsock != null) {
                // One time attempt a socket close
                final DatagramChannel tmp2 = errsock;
                errsock = null;
                // Could throw, but errsock cleared for next pass
                tmp2.close();
            }
            // prevent deny-of-service endless socket-creates
            if (saw_error)
                Thread.sleep(1000);
            saw_error = false;
            // Common-case setup of a socket
            if (sock == null) {
                sock = DatagramChannel.open();
                sock.socket().bind(H2O.SELF._key);
            }
            // Receive a packet & handle it
            basic_packet_handling(new AutoBuffer(sock));
        } catch (java.nio.channels.AsynchronousCloseException ex) {
            break;
        } catch (java.nio.channels.ClosedChannelException ex) {
            break;
        } catch (Exception e) {
            Log.err("UDP Receiver error on port " + H2O.H2O_PORT, e);
            saw_error = true;
            errsock = sock;
            sock = null;
        }
    }
}

50. MediaDriver#validateSufficientSocketBufferLengths()

Project: Aeron
File: MediaDriver.java
private static void validateSufficientSocketBufferLengths(final Context ctx) {
    try (final DatagramChannel probe = DatagramChannel.open()) {
        final int defaultSoSndBuf = probe.getOption(StandardSocketOptions.SO_SNDBUF);
        probe.setOption(StandardSocketOptions.SO_SNDBUF, Integer.MAX_VALUE);
        final int maxSoSndBuf = probe.getOption(StandardSocketOptions.SO_SNDBUF);
        if (maxSoSndBuf < SOCKET_SNDBUF_LENGTH) {
            System.err.format("WARNING: Could not get desired SO_SNDBUF, adjust OS buffer to match %s: attempted=%d, actual=%d%n", SOCKET_SNDBUF_LENGTH_PROP_NAME, SOCKET_SNDBUF_LENGTH, maxSoSndBuf);
        }
        probe.setOption(StandardSocketOptions.SO_RCVBUF, Integer.MAX_VALUE);
        final int maxSoRcvBuf = probe.getOption(StandardSocketOptions.SO_RCVBUF);
        if (maxSoRcvBuf < SOCKET_RCVBUF_LENGTH) {
            System.err.format("WARNING: Could not get desired SO_RCVBUF, adjust OS buffer to match %s: attempted=%d, actual=%d%n", SOCKET_RCVBUF_LENGTH_PROP_NAME, SOCKET_RCVBUF_LENGTH, maxSoRcvBuf);
        }
        final int soSndBuf = 0 == SOCKET_SNDBUF_LENGTH ? defaultSoSndBuf : SOCKET_SNDBUF_LENGTH;
        if (ctx.mtuLength() > soSndBuf) {
            throw new ConfigurationException(String.format("MTU greater than socket SO_SNDBUF, adjust %s to match MTU: mtuLength=%d, SO_SNDBUF=%d", SOCKET_SNDBUF_LENGTH_PROP_NAME, ctx.mtuLength(), soSndBuf));
        }
    } catch (final IOException ex) {
        throw new RuntimeException(String.format("probe socket: %s", ex.toString()), ex);
    }
}