use of java.nio.channels.DatagramChannel in project robovm by robovm.
the class OldDatagramSocketTest method test_receiveLjava_net_DatagramPacket.
public void test_receiveLjava_net_DatagramPacket() throws Exception {
// Test for method void
// java.net.DatagramSocket.receive(java.net.DatagramPacket)
receive_oversize_java_net_DatagramPacket();
final int[] ports = Support_PortManager.getNextPortsForUDP(2);
final int portNumber = ports[0];
class TestDGRcv implements Runnable {
public void run() {
try {
InetAddress localHost = InetAddress.getLocalHost();
Thread.sleep(1000);
DatagramSocket sds = new DatagramSocket(ports[1]);
sds.send(new DatagramPacket("Test".getBytes("UTF-8"), "Test".length(), localHost, portNumber));
sds.send(new DatagramPacket("Longer test".getBytes("UTF-8"), "Longer test".length(), localHost, portNumber));
sds.send(new DatagramPacket("3 Test".getBytes("UTF-8"), "3 Test".length(), localHost, portNumber));
sds.send(new DatagramPacket("4 Test".getBytes("UTF-8"), "4 Test".length(), localHost, portNumber));
sds.send(new DatagramPacket("5".getBytes("UTF-8"), "5".length(), localHost, portNumber));
sds.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
try {
new Thread(new TestDGRcv(), "datagram receiver").start();
ds = new java.net.DatagramSocket(portNumber);
ds.setSoTimeout(6000);
byte[] rbuf = new byte[1000];
DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
// Receive the first packet.
ds.receive(rdp);
assertEquals("Test", new String(rbuf, 0, rdp.getLength()));
// Check that we can still receive a longer packet (http://code.google.com/p/android/issues/detail?id=24748).
ds.receive(rdp);
assertEquals("Longer test", new String(rbuf, 0, rdp.getLength()));
// See what happens if we manually call DatagramPacket.setLength.
rdp.setLength(4);
ds.receive(rdp);
assertEquals("3 Te", new String(rbuf, 0, rdp.getLength()));
// And then another.
ds.receive(rdp);
assertEquals("4 Te", new String(rbuf, 0, rdp.getLength()));
// And then a packet shorter than the user-supplied length.
ds.receive(rdp);
assertEquals("5", new String(rbuf, 0, rdp.getLength()));
ds.close();
} finally {
ds.close();
}
DatagramSocket socket = null;
try {
byte[] rbuf = new byte[1000];
DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
socket = channel.socket();
socket.receive(rdp);
fail("IllegalBlockingModeException was not thrown.");
} catch (IllegalBlockingModeException expected) {
} finally {
socket.close();
}
try {
ds = new java.net.DatagramSocket(portNumber);
ds.setSoTimeout(1000);
byte[] rbuf = new byte[1000];
DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
ds.receive(rdp);
fail("SocketTimeoutException was not thrown.");
} catch (SocketTimeoutException expected) {
} finally {
ds.close();
}
interrupted = false;
final DatagramSocket ds = new DatagramSocket();
ds.setSoTimeout(12000);
Runnable runnable = new Runnable() {
public void run() {
try {
ds.receive(new DatagramPacket(new byte[1], 1));
} catch (InterruptedIOException e) {
interrupted = true;
} catch (IOException ignored) {
}
}
};
Thread thread = new Thread(runnable, "DatagramSocket.receive1");
thread.start();
do {
Thread.sleep(500);
} while (!thread.isAlive());
ds.close();
int c = 0;
do {
Thread.sleep(500);
if (interrupted) {
fail("received interrupt");
}
if (++c > 4) {
fail("read call did not exit");
}
} while (thread.isAlive());
interrupted = false;
final int portNum = ports[0];
final DatagramSocket ds2 = new DatagramSocket(ports[1]);
ds2.setSoTimeout(12000);
Runnable runnable2 = new Runnable() {
public void run() {
try {
ds2.receive(new DatagramPacket(new byte[1], 1, InetAddress.getLocalHost(), portNum));
} catch (InterruptedIOException e) {
interrupted = true;
} catch (IOException ignored) {
}
}
};
Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
thread2.start();
try {
do {
Thread.sleep(500);
} while (!thread2.isAlive());
} catch (InterruptedException ignored) {
}
ds2.close();
int c2 = 0;
do {
Thread.sleep(500);
if (interrupted) {
fail("receive2 was interrupted");
}
if (++c2 > 4) {
fail("read2 call did not exit");
}
} while (thread2.isAlive());
interrupted = false;
DatagramSocket ds3 = new DatagramSocket();
ds3.setSoTimeout(500);
Date start = new Date();
try {
ds3.receive(new DatagramPacket(new byte[1], 1));
} catch (InterruptedIOException e) {
interrupted = true;
}
ds3.close();
assertTrue("receive not interrupted", interrupted);
int delay = (int) (new Date().getTime() - start.getTime());
assertTrue("timeout too soon: " + delay, delay >= 490);
}
use of java.nio.channels.DatagramChannel in project h2o-3 by h2oai.
the class UDPReceiverThread method run.
// ---
// 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) {
// Socket closed for shutdown
break;
} catch (java.nio.channels.ClosedChannelException ex) {
// Socket closed for shutdown
break;
} catch (Exception e) {
// On any error from anybody, close all sockets & re-open
Log.err("UDP Receiver error on port " + H2O.H2O_PORT, e);
saw_error = true;
errsock = sock;
// Signal error recovery on the next loop
sock = null;
}
}
}
use of java.nio.channels.DatagramChannel in project Aeron by real-logic.
the class TransferToPing method main.
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);
}
}
use of java.nio.channels.DatagramChannel in project robovm by robovm.
the class DatagramChannelTest method testNonBlockingRecv.
// 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();
}
}
use of java.nio.channels.DatagramChannel in project nifi by apache.
the class ChannelDispatcher method selectSocketChannelKeys.
/*
* When invoking this method, only want to iterate through the selected keys once. When a key is entered into the selectors
* selected key set, select will return a positive value. The next select will return 0 if nothing has changed. Note that
* the selected key set is not manually changed via a remove operation.
*
* @throws IOException if unable to select keys
*/
private void selectSocketChannelKeys() throws IOException {
// once a channel associated with a key in this selector is 'ready', it causes this select to immediately return.
// thus, for each trip through the run() we only get hit with one real timeout...the one in selectServerSocketKeys.
int numSelected = socketChannelSelector.select(timeout);
if (numSelected == 0) {
return;
}
for (SelectionKey socketChannelKey : socketChannelSelector.selectedKeys()) {
final SelectableChannel channel = socketChannelKey.channel();
AbstractChannelReader reader = null;
// way to tell if it's new is the lack of an attachment.
if (channel instanceof DatagramChannel && socketChannelKey.attachment() == null) {
reader = new DatagramChannelReader(UUID.randomUUID().toString(), socketChannelKey, emptyBuffers, factory, readSingleDatagram);
socketChannelKey.attach(reader);
final ScheduledFuture<?> readerFuture = executor.scheduleWithFixedDelay(reader, 10L, channelReaderFrequencyMilliseconds.get(), TimeUnit.MILLISECONDS);
reader.setScheduledFuture(readerFuture);
}
if (reader != null && LOGGER.isDebugEnabled()) {
LOGGER.debug(this + " New Connection established. Server channel: " + channel + " Reader: " + reader);
}
}
}
Aggregations