Java Code Examples for java.nio.channels.DatagramChannel

The following examples show how to use java.nio.channels.DatagramChannel. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: mldht   Source File: OpentrackerLiveSync.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@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 2
Source Project: codeone2019-java-profiling   Source File: DatagramTest.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: openjdk-jdk9   Source File: UseDGWithIPv6.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 4
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 Project: mts   Source File: DatagramReactor.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 Project: TencentKona-8   Source File: UseDGWithIPv6.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 7
Source Project: jdk8u-jdk   Source File: UseDGWithIPv6.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 8
Source Project: TarsJava   Source File: Server.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 9
Source Project: android-netty   Source File: SocketSendBufferPool.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: j2objc   Source File: DatagramChannelTest.java    License: Apache License 2.0 6 votes vote down vote up
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 11
Source Project: localization_nifi   Source File: DatagramChannelSender.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: jdk8u-dev-jdk   Source File: UseDGWithIPv6.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 13
/** {@inheritDoc} */
@Override
public Closeable registerChannel(String name, DatagramChannel channel) {
    final ManagedBinding binding = new CloseableManagedBinding(name, (InetSocketAddress) channel.socket().getLocalSocketAddress(), channel, this);
    registerBinding(binding);
    return binding;
}
 
Example 14
Source Project: Tomcat7.0.67   Source File: NioReplicationTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
 * that it should always go to the buffer
 * @param key
 * @param channel
 */
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
    try {

        ByteBuffer buf = ByteBuffer.wrap(command);
        int total = 0;
        if (channel instanceof DatagramChannel) {
            DatagramChannel dchannel = (DatagramChannel)channel;
            //were using a shared channel, document says its thread safe
            //TODO check optimization, one channel per thread?
            while ( total < command.length ) {
                total += dchannel.send(buf, udpaddr);
            }
        } else {
            while ( total < command.length ) {
                total += channel.write(buf);
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("ACK sent to " +
                    ( (channel instanceof SocketChannel) ?
                      ((SocketChannel)channel).socket().getInetAddress() :
                      ((DatagramChannel)channel).socket().getInetAddress()));
        }
    } catch ( java.io.IOException x ) {
        log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
    }
}
 
Example 15
Source Project: hottub   Source File: ChangingAddress.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 16
Source Project: gnirehtet   Source File: UDPConnection.java    License: Apache License 2.0 5 votes vote down vote up
private DatagramChannel createChannel() throws IOException {
    logi(TAG, "Open");
    DatagramChannel datagramChannel = DatagramChannel.open();
    datagramChannel.configureBlocking(false);
    datagramChannel.connect(getRewrittenDestination());
    return datagramChannel;
}
 
Example 17
Source Project: phoebus   Source File: Network.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** Create UDP channel
 *
 *  @param broadcast Support broadcast?
 *  @param port Port to use or 0 to auto-assign
 *  @return UDP channel
 *  @throws Exception on error
 */
public static DatagramChannel createUDP(boolean broadcast, int port) throws Exception
{
    // Current use of multicast addresses works only with INET, not INET6
    final DatagramChannel udp = DatagramChannel.open(StandardProtocolFamily.INET);
    udp.configureBlocking(true);
    if (broadcast)
        udp.socket().setBroadcast(true);
    udp.socket().setReuseAddress(true);
    udp.bind(new InetSocketAddress(port));
    return udp;
}
 
Example 18
Source Project: openjdk-jdk9   Source File: ChangingAddress.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 19
Source Project: netty4.0.27Learn   Source File: NioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
@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 20
Source Project: dragonwell8_jdk   Source File: NotBound.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void wakeupWhenBound(final DatagramChannel dc) {
    Runnable wakeupTask = new Runnable() {
        public void run() {
            try {
                // poll for local address
                InetSocketAddress local;
                do {
                    Thread.sleep(50);
                    local = (InetSocketAddress)dc.getLocalAddress();
                } while (local == null);

                // send message to channel to wakeup receiver
                DatagramChannel sender = DatagramChannel.open();
                try {
                    ByteBuffer bb = ByteBuffer.wrap("hello".getBytes());
                    InetAddress lh = InetAddress.getLocalHost();
                    SocketAddress target =
                        new InetSocketAddress(lh, local.getPort());
                    sender.send(bb, target);
                } finally {
                    sender.close();
                }

            } catch (Exception x) {
                x.printStackTrace();
            }
        }};
    new Thread(wakeupTask).start();
}
 
Example 21
public void open(SocketAddress bindAddress, SocketAddress peerAddress) throws IOException {
    channel = DatagramChannel.open();
    channel.socket().bind(bindAddress);
    channel.configureBlocking(false);
    channel.connect(peerAddress);
    stream = new MAVLinkStream(schema, channel);
    stream.setDebug(debug);
}
 
Example 22
Source Project: netty-4.1.22   Source File: NioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
private static DatagramChannel newSocket(SelectorProvider provider) {
    try {
        /**
         *  Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
         *  {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
         *
         *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
         */
        return provider.openDatagramChannel();
    } catch (IOException e) {
        throw new ChannelException("Failed to open a socket.", e);
    }
}
 
Example 23
Source Project: netty-4.1.22   Source File: NioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
@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 24
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 25
Source Project: netty-4.1.22   Source File: NioDatagramChannel.java    License: Apache License 2.0 5 votes vote down vote up
@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 26
Source Project: Voovan   Source File: UdpSocket.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构造函数
 * @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 27
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 28
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 29
Source Project: perfmon-agent   Source File: PerfMonMetricGetterTest.java    License: Apache License 2.0 5 votes vote down vote up
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 30
Source Project: j2objc   Source File: DatagramChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}