java.nio.channels.DatagramChannel Java Examples
The following examples show how to use
java.nio.channels.DatagramChannel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UseDGWithIPv6.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
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) { //This regression test is to check vm crash only, so ioe is OK. e.printStackTrace(); } } dgChannel.close(); }
Example #2
Source File: UseDGWithIPv6.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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) { //This regression test is to check vm crash only, so ioe is OK. e.printStackTrace(); } } dgChannel.close(); }
Example #3
Source File: DatagramChannelTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testReadWrite_Block_WriterNotBound() throws Exception { byte[] sourceArray = new byte[CAPACITY_NORMAL]; byte[] targetArray = new byte[CAPACITY_NORMAL]; for (int i = 0; i < sourceArray.length; i++) { sourceArray[i] = (byte) i; } DatagramChannel dc = DatagramChannel.open(); // The writer isn't bound, but is connected. dc.connect(channel1Address); // write ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray); assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf)); // Connect channel2 after data has been written. channel2.connect(dc.socket().getLocalSocketAddress()); // read ByteBuffer targetBuf = ByteBuffer.wrap(targetArray); closeBlockedReaderChannel2(targetBuf); dc.close(); }
Example #4
Source File: AbstractDatagramChannelBinding.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
protected void configureListenerChannel() { // open the listener port try { listenerChannel = DatagramChannel.open(); listenerChannel.socket().bind(new InetSocketAddress(listenerPort)); listenerChannel.configureBlocking(false); logger.info("Listening for incoming data on {}", listenerChannel.getLocalAddress()); synchronized (selector) { selector.wakeup(); try { listenerKey = listenerChannel.register(selector, listenerChannel.validOps()); } catch (ClosedChannelException e1) { logger.warn("An exception occurred while registering a selector: {}", e1.getMessage()); } } } catch (Exception e3) { logger.warn("An exception occurred while creating the Listener Channel on port number {} ({})", listenerPort, e3.getMessage()); } }
Example #5
Source File: DatagramReactor.java From mts with GNU General Public License v3.0 | 6 votes |
public void open(SocketAddress localSocketAddress, DatagramHandler handler) throws Exception { // Create a non-blocking socket channel DatagramChannel channel = DatagramChannel.open(); // read all properties for the UDP socket Config.getConfigForUDPSocket(channel.socket()); channel.socket().bind(localSocketAddress); channel.configureBlocking(false); synchronized(selectorLock) { this.selector.wakeup(); handler.init(channel.register(selector, SelectionKey.OP_READ, handler)); } }
Example #6
Source File: DatagramChannelSender.java From localization_nifi with Apache License 2.0 | 6 votes |
@Override public void open() throws IOException { if (channel == null) { channel = DatagramChannel.open(); if (maxSendBufferSize > 0) { channel.setOption(StandardSocketOptions.SO_SNDBUF, maxSendBufferSize); final int actualSendBufSize = channel.getOption(StandardSocketOptions.SO_SNDBUF); if (actualSendBufSize < maxSendBufferSize) { logger.warn("Attempted to set Socket Send Buffer Size to " + maxSendBufferSize + " bytes but could only set to " + actualSendBufSize + "bytes. You may want to " + "consider changing the Operating System's maximum receive buffer"); } } } if (!channel.isConnected()) { channel.connect(new InetSocketAddress(InetAddress.getByName(host), port)); } }
Example #7
Source File: SocketSendBufferPool.java From android-netty with Apache License 2.0 | 6 votes |
public long transferTo(DatagramChannel ch, SocketAddress raddr) throws IOException { int send = 0; for (ByteBuffer buf: buffers) { if (buf.hasRemaining()) { int w = ch.send(buf, raddr); if (w == 0) { break; } else { send += w; } } } written += send; return send; }
Example #8
Source File: DatagramTest.java From codeone2019-java-profiling with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { ch = DatagramChannel.open(); ch.bind(new InetSocketAddress(5555)); ch.configureBlocking(false); Executor pool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { pool.execute(DatagramTest::sendLoop); } System.out.println("Warming up..."); Thread.sleep(3000); totalPackets.set(0); System.out.println("Benchmarking..."); Thread.sleep(5000); System.out.println(totalPackets.get() / 5); System.exit(0); }
Example #9
Source File: UseDGWithIPv6.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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) { //This regression test is to check vm crash only, so ioe is OK. e.printStackTrace(); } } dgChannel.close(); }
Example #10
Source File: OpentrackerLiveSync.java From mldht with Mozilla Public License 2.0 | 6 votes |
@Override public void start(Collection<DHT> dhts, ConfigReader config) { try { channel = DatagramChannel.open(StandardProtocolFamily.INET); channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, 1); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); // we only need to send, not to receive, so need to bind to a specific port channel.bind(new InetSocketAddress(0)); channel.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] {(byte) 224,0,23,5}), 9696)); } catch (IOException e) { e.printStackTrace(); return; } t.setDaemon(true); t.setName("opentracker-sync"); t.start(); // OT-sync only supports ipv4 atm dhts.stream().filter(d -> d.getType().PREFERRED_ADDRESS_TYPE == Inet4Address.class).forEach(d -> { d.addIncomingMessageListener(this::incomingPacket); }); }
Example #11
Source File: UseDGWithIPv6.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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) { //This regression test is to check vm crash only, so ioe is OK. e.printStackTrace(); } } dgChannel.close(); }
Example #12
Source File: Server.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected void startNIOServer() throws Exception { SelectableChannel server = null; int interestKey; //1. Start reactor service selectorManager.start(); //2. Start server on the specified port if (this.udpMode) { server = DatagramChannel.open(); ((DatagramChannel) server).socket().bind(new InetSocketAddress(host, port)); interestKey = SelectionKey.OP_READ; } else { server = ServerSocketChannel.open(); ((ServerSocketChannel) server).socket().bind(new InetSocketAddress(host, port), 1024); interestKey = SelectionKey.OP_ACCEPT; } server.configureBlocking(false); //3. Choose one reactor to handle NIO event selectorManager.getReactor(0).registerChannel(server, interestKey); System.out.println("INFO: NAMI Server started on port " + String.valueOf(port) + "..."); }
Example #13
Source File: NioUDPDataSender.java From pinpoint with Apache License 2.0 | 5 votes |
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) { IOUtils.closeQuietly(socket); IOUtils.closeQuietly(datagramChannel); throw new IllegalStateException("DatagramChannel create fail. Cause" + e.getMessage(), e); } }
Example #14
Source File: PreferIPv6AddressesTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
static boolean IPv6Supported() throws IOException { try { DatagramChannel.open(StandardProtocolFamily.INET6); return true; } catch (UnsupportedOperationException x) { return false; } }
Example #15
Source File: NioDatagramChannel.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("deprecation") public boolean isActive() { DatagramChannel ch = javaChannel(); return ch.isOpen() && ( config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered() || ch.socket().isBound()); }
Example #16
Source File: NioDatagramChannel.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override @SuppressWarnings("deprecation") public boolean isActive() { DatagramChannel ch = javaChannel(); return ch.isOpen() && ( config.getOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION) && isRegistered() || ch.socket().isBound()); }
Example #17
Source File: AbstractDatagramChannelBinding.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
public ArrayList<Channel> getAll(Direction direction, DatagramChannel theDatagramChannel) { synchronized (this) { ArrayList<Channel> selectedChannels = new ArrayList<Channel>(); Iterator<C> it = iterator(); while (it.hasNext()) { C aChannel = it.next(); if (theDatagramChannel.equals(aChannel.channel) && direction.equals(aChannel.direction)) { selectedChannels.add(aChannel); } } return selectedChannels; } }
Example #18
Source File: NioDatagramChannel.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@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(); } } }
Example #19
Source File: UdpSocket.java From Voovan with Apache License 2.0 | 5 votes |
/** * 构造函数 * @param parentSocketContext 父 SocketChannel 对象 * @param datagramChannel UDP通信对象 * @param socketAddress SocketAddress 对象 */ public UdpSocket(SocketContext parentSocketContext, DatagramChannel datagramChannel, InetSocketAddress socketAddress){ try { this.provider = SelectorProvider.provider(); this.datagramChannel = datagramChannel; this.copyFrom(parentSocketContext); this.session = new UdpSession(this, socketAddress); this.datagramChannel.configureBlocking(false); this.connectModel = ConnectModel.SERVER; this.connectType = ConnectType.UDP; } catch (Exception e) { Logger.error("Create socket channel failed",e); } }
Example #20
Source File: ChangingAddress.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
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(); } }
Example #21
Source File: DatagramChannelTest.java From j2objc with Apache License 2.0 | 5 votes |
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(); }
Example #22
Source File: ChangingAddress.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
static void check(DatagramSocket ds, DatagramChannel dc) { InetAddress expected = ds.getLocalAddress(); InetAddress actual = dc.socket().getLocalAddress(); // okay if one bound to 0.0.0.0 and the other to ::0 if ((expected.isAnyLocalAddress() != actual.isAnyLocalAddress()) && !expected.equals(actual)) { throw new RuntimeException("Expected: " + expected + ", actual: " + actual); } }
Example #23
Source File: ChangingAddress.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
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(); } }
Example #24
Source File: AbstractDatagramChannelBinding.java From openhab1-addons with Eclipse Public License 2.0 | 5 votes |
public void replace(Direction direction, InetSocketAddress remoteAddress, DatagramChannel channel) { synchronized (this) { Iterator<C> it = iterator(); while (it.hasNext()) { C aChannel = it.next(); if (remoteAddress.equals(aChannel.remote) && direction.equals(aChannel.direction) && !channel.equals(aChannel.channel)) { aChannel.channel = channel; } } } }
Example #25
Source File: DatagramChannelTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * @tests DatagramChannel#read(ByteBuffer) */ public void test_read_LByteBuffer_closed_nullBuf() throws Exception { // regression test for Harmony-754 ByteBuffer c = null; DatagramChannel channel = DatagramChannel.open(); channel.close(); try{ channel.read(c); fail("Should throw NullPointerException"); } catch (NullPointerException e){ // expected } }
Example #26
Source File: JdpBroadcaster.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Create a new broadcaster * * @param address - multicast group address * @param srcAddress - address of interface we should use to broadcast. * @param port - udp port to use * @param ttl - packet ttl * @throws IOException */ public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl) throws IOException, JdpException { this.addr = address; this.port = port; ProtocolFamily family = (address instanceof Inet6Address) ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET; channel = DatagramChannel.open(family); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl); // with srcAddress equal to null, this constructor do exactly the same as // if srcAddress is not passed if (srcAddress != null) { // User requests particular interface to bind to NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress); if (interf == null) { throw new JdpException("Unable to get network interface for " + srcAddress.toString()); } if (!interf.isUp()) { throw new JdpException(interf.getName() + " is not up."); } if (!interf.supportsMulticast()) { throw new JdpException(interf.getName() + " does not support multicast."); } try { channel.bind(new InetSocketAddress(srcAddress, 0)); } catch (UnsupportedAddressTypeException ex) { throw new JdpException("Unable to bind to source address"); } channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf); } }
Example #27
Source File: UdpSocketHandlerTest.java From datakernel with Apache License 2.0 | 5 votes |
@Test public void testEchoUdpServer() throws IOException { DatagramChannel serverDatagramChannel = createDatagramChannel(DatagramSocketSettings.create(), SERVER_ADDRESS, null); AsyncUdpSocketNio.connect(Eventloop.getCurrentEventloop(), serverDatagramChannel) .then(serverSocket -> serverSocket.receive() .then(serverSocket::send) .whenComplete(serverSocket::close)) .whenComplete(assertComplete()); DatagramChannel clientDatagramChannel = createDatagramChannel(DatagramSocketSettings.create(), null, null); Promise<AsyncUdpSocketNio> promise = AsyncUdpSocketNio.connect(Eventloop.getCurrentEventloop(), clientDatagramChannel) .whenComplete(assertComplete(clientSocket -> { clientSocket.send(UdpPacket.of(ByteBuf.wrapForReading(bytesToSend), SERVER_ADDRESS)) .whenComplete(assertComplete()); clientSocket.receive() .whenComplete(clientSocket::close) .whenComplete(assertComplete(packet -> { byte[] message = packet.getBuf().asArray(); assertArrayEquals(bytesToSend, message); System.out.println("message = " + Arrays.toString(message)); })); })); await(promise); }
Example #28
Source File: PerfMonMetricGetterTest.java From perfmon-agent with Apache License 2.0 | 5 votes |
public void testProcessNextCommand() throws Exception { System.out.println("processNextCommand"); PerfMonMetricGetter instance = new PerfMonMetricGetter( SigarProxyCache.newInstance(new Sigar(), 500), new PerfMonWorker(), DatagramChannel.open()); boolean expResult = false; boolean result = instance.processNextCommand(); assertEquals(expResult, result); }
Example #29
Source File: NioDatagramAcceptor.java From neoscada with Eclipse Public License 1.0 | 5 votes |
@Override protected boolean isReadable(DatagramChannel handle) { SelectionKey key = handle.keyFor(selector); if ((key == null) || (!key.isValid())) { return false; } return key.isReadable(); }
Example #30
Source File: DatagramChannelTest.java From j2objc with Apache License 2.0 | 5 votes |
public void test_bind_null() throws Exception { DatagramChannel dc = DatagramChannel.open(); try { assertNull(dc.socket().getLocalSocketAddress()); dc.socket().bind(null); InetSocketAddress localAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress(); assertTrue(localAddress.getAddress().isAnyLocalAddress()); assertTrue(localAddress.getPort() > 0); } finally { dc.close(); } }