Java Code Examples for java.nio.channels.DatagramChannel#bind()

The following examples show how to use java.nio.channels.DatagramChannel#bind() . 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: ChannelListener.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final DatagramChannel dChannel = DatagramChannel.open();
    dChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dChannel.bind(new InetSocketAddress(nicIPAddress, port));
    return dChannel;
}
 
Example 2
Source File: ChannelListener.java    From nifi with Apache License 2.0 6 votes vote down vote up
private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final DatagramChannel dChannel = DatagramChannel.open();
    dChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        dChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = dChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set UDP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    dChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dChannel.bind(new InetSocketAddress(nicIPAddress, port));
    return dChannel;
}
 
Example 3
Source File: MarketData.java    From parity-extras with Apache License 2.0 6 votes vote down vote up
public static MarketData open(NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
        long instrument) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress(multicastGroup.getPort()));
    channel.join(multicastGroup.getAddress(), multicastInterface);
    channel.configureBlocking(false);

    DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);

    requestChannel.configureBlocking(false);

    return new MarketData(channel, requestChannel, requestAddress, instrument);
}
 
Example 4
Source File: UDPSampler.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
protected AbstractSelectableChannel getChannel() throws IOException {
    DatagramChannel c;
    if (isWaitResponse()) {
        c = DatagramChannelWithTimeouts.open();
        ((DatagramChannelWithTimeouts) c).setReadTimeout(getTimeoutAsInt());
    } else {
        c = DatagramChannel.open();
    }

    String bindAddress = getBindAddress();
    if (bindAddress.isEmpty()) {
        bindAddress = "0.0.0.0";
    }
    int adr = getBindPortAsInt();
    c.bind(new InetSocketAddress(bindAddress, adr));

    int port = Integer.parseInt(getPort());
    c.connect(new InetSocketAddress(getHostName(), port));
    return c;
}
 
Example 5
Source File: MulticastTest.java    From mpush with Apache License 2.0 6 votes vote down vote up
@Test
public void TestServer() throws Exception {
    //接受组播和发送组播的数据报服务都要把组播地址添加进来
    String host = "239.239.239.88";//多播地址
    int port = 9998;
    InetAddress group = InetAddress.getByName(host);

    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
    channel.bind(new InetSocketAddress(port));
    channel.join(group, Utils.getLocalNetworkInterface());
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    SocketAddress sender = channel.receive(buffer);
    buffer.flip();
    byte[] data = new byte[buffer.remaining()];
    buffer.get(data);
    System.out.println(new String(data));

}
 
Example 6
Source File: TestNonBlockingNIO2.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void receive() throws IOException {
    DatagramChannel dc = DatagramChannel.open();
    dc.configureBlocking(false);
    dc.bind(new InetSocketAddress(9898));
    Selector selector = Selector.open();
    dc.register(selector, SelectionKey.OP_READ);
    while (selector.select() > 0) {
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();

            if (sk.isReadable()) {
                ByteBuffer buf = ByteBuffer.allocate(1024);
                dc.receive(buf)
                ;
                buf.flip();
                System.out.println(new String(buf.array(), 0, buf.limit()));
                buf.clear();
            }
        }
        it.remove();
    }
}
 
Example 7
Source File: EmptyBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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();
    }
}
 
Example 8
Source File: Network.java    From phoebus with 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 9
Source File: AnnounceGroupChannel.java    From bt with Apache License 2.0 5 votes vote down vote up
private synchronized DatagramChannel getChannel() throws IOException {
    if (channel == null || !channel.isOpen()) {
        if (shutdown.get()) {
            throw new IllegalStateException("Channel has been shut down");
        }
        ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
        DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
        _channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        // bind to any-local before setting TTL
        int port = group.getAddress().getPort();
        if (protocolFamily == StandardProtocolFamily.INET) {
            _channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
        } else {
            _channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
        }
        int timeToLive = group.getTimeToLive();
        if (timeToLive != 1) {
            _channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
        }

        for (NetworkInterface iface : networkInterfaces) {
            _channel.join(group.getAddress().getAddress(), iface);
        }

        _channel.configureBlocking(false);
        channel = _channel;
    }
    return channel;
}
 
Example 10
Source File: EmptyDatagramTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlockSockets() throws Exception {
    DatagramChannel channel1 = DatagramChannel.open();
    channel1.configureBlocking(true);
    // No empty datagram for connected socket
    // https://bugs.openjdk.java.net/browse/JDK-8013175
    // channel1.connect(bindAddress);

    DatagramChannel channel2 = DatagramChannel.open();
    channel2.configureBlocking(true);
    channel2.bind(REFLECTOR_ADDRESS);

    ByteBuffer bb = ByteBuffer.allocate(0);
    bb.clear();

    try {
        bb.flip();
        int sent = channel1.send(bb, REFLECTOR_ADDRESS);
        Assert.assertEquals(0, sent);

        Thread.sleep(100);

        bb.clear();
        InetSocketAddress address = (InetSocketAddress) channel2.receive(bb);
        Assert.assertNotNull(address);
        Assert.assertEquals(0, bb.position());
    } finally {
        NioUtils.close(channel2);
        NioUtils.close(channel1);
    }
}
 
Example 11
Source File: TestNonBlockingNIO2.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void receive() throws IOException {
    DatagramChannel dc = DatagramChannel.open();

    dc.configureBlocking(false);

    dc.bind(new InetSocketAddress(9898));

    Selector selector = Selector.open();

    dc.register(selector, SelectionKey.OP_READ);

    while (selector.select() > 0) {
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();

        while (it.hasNext()) {
            SelectionKey sk = it.next();

            if (sk.isReadable()) {
                ByteBuffer buf = ByteBuffer.allocate(1024);

                dc.receive(buf);
                buf.flip();
                System.out.println(new String(buf.array(), 0, buf.limit()));
                buf.clear();
            }
        }

        it.remove();
    }
}
 
Example 12
Source File: MoldUDP64.java    From nassau with Apache License 2.0 5 votes vote down vote up
/**
 * Receive messages. Invoke the message listener on each message. Continue
 * until a packet indicating the End of Session is received.
 *
 * @param multicastInterface the multicast interface
 * @param multicastGroup the multicast group
 * @param requestAddress the request address
 * @param listener a message listener
 * @throws IOException if an I/O error occurs
 */
public static void receive(NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup, InetSocketAddress requestAddress,
        MessageListener listener) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress(multicastGroup.getPort()));
    channel.join(multicastGroup.getAddress(), multicastInterface);
    channel.configureBlocking(false);

    DatagramChannel requestChannel = DatagramChannel.open(StandardProtocolFamily.INET);

    requestChannel.configureBlocking(false);

    StatusListener statusListener = new StatusListener();

    try (Selector selector = Selector.open();
            MoldUDP64Client client = new MoldUDP64Client(channel, requestChannel,
                requestAddress, listener, statusListener)) {
        SelectionKey channelKey = channel.register(selector, SelectionKey.OP_READ);

        SelectionKey requestChannelKey = requestChannel.register(selector, SelectionKey.OP_READ);

        while (statusListener.receive) {
            while (selector.select() == 0);

            Set<SelectionKey> selectedKeys = selector.selectedKeys();

            if (selectedKeys.contains(channelKey))
                client.receive();

            if (selectedKeys.contains(requestChannelKey))
                client.receiveResponse();

            selectedKeys.clear();
        }
    }
}
 
Example 13
Source File: DatagramChannels.java    From nassau with Apache License 2.0 5 votes vote down vote up
static DatagramChannel openClientChannel() throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.bind(null);
    channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, loopbackInterface());
    channel.join(multicastGroup(), loopbackInterface());

    return channel;
}
 
Example 14
Source File: TestServer.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param port
 * @param addr
 * @return
 * @throws Exception
 */
public static DatagramChannel createDatagramChannel(int port, InetAddress addr) throws Exception {
	final DatagramChannel channel = DatagramChannel.open();
	if (addr == null) {
		channel.bind(new InetSocketAddress(port));
	}
	else {
		channel.bind(new InetSocketAddress(addr, port));
	}
	
	return channel;
}
 
Example 15
Source File: LifxSelectorUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
public static @Nullable SelectionKey openBroadcastChannel(@Nullable Selector selector, String logId,
        int broadcastPort) throws IOException {
    if (selector == null) {
        return null;
    }
    DatagramChannel broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
            .setOption(StandardSocketOptions.SO_REUSEADDR, true)
            .setOption(StandardSocketOptions.SO_BROADCAST, true);
    broadcastChannel.configureBlocking(false);
    LOGGER.debug("{} : Binding the broadcast channel on port {}", logId, broadcastPort);
    broadcastChannel.bind(new InetSocketAddress(broadcastPort));
    return broadcastChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
 
Example 16
Source File: SelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
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();
        }
    }
}
 
Example 17
Source File: HackSelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 18
Source File: MarketData.java    From parity with Apache License 2.0 4 votes vote down vote up
static MarketData open(String session, NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup,
        InetSocketAddress requestAddress) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
    channel.connect(multicastGroup);

    MoldUDP64Server transport = new MoldUDP64Server(channel, session);

    DatagramChannel requestChannel = DatagramChannel.open();

    requestChannel.bind(requestAddress);
    requestChannel.configureBlocking(false);

    MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);

    return new MarketData(transport, requestTransport);
}
 
Example 19
Source File: MarketReporting.java    From parity with Apache License 2.0 4 votes vote down vote up
static MarketReporting open(String session, NetworkInterface multicastInterface,
        InetSocketAddress multicastGroup,
        InetSocketAddress requestAddress) throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, multicastInterface);
    channel.connect(multicastGroup);

    MoldUDP64Server transport = new MoldUDP64Server(channel, session);

    DatagramChannel requestChannel = DatagramChannel.open();

    requestChannel.bind(requestAddress);
    requestChannel.configureBlocking(false);

    MoldUDP64RequestServer requestTransport = new MoldUDP64RequestServer(requestChannel);

    return new MarketReporting(transport, requestTransport);
}
 
Example 20
Source File: DatagramChannels.java    From nassau with Apache License 2.0 3 votes vote down vote up
static DatagramChannel openServerRequestChannel() throws IOException {
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);

    channel.bind(null);

    return channel;
}