Example usage for java.nio.channels DatagramChannel bind

List of usage examples for java.nio.channels DatagramChannel bind

Introduction

In this page you can find the example usage for java.nio.channels DatagramChannel bind.

Prototype

public abstract DatagramChannel bind(SocketAddress local) throws IOException;

Source Link

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    server.bind(null);
    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    server.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    String msg = "Hello!";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress group = new InetSocketAddress(MULTICAST_IP, MULTICAST_PORT);

    server.send(buffer, group);/*from w  w w .j  a  v  a  2 s . co  m*/
    System.out.println("Sent the   multicast  message: " + msg);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DatagramChannel client = null;
    client = DatagramChannel.open();

    client.bind(null);

    String msg = "Hello";
    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
    InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989);

    client.send(buffer, serverAddress);/* ww  w  .j  av  a2s  .  c  om*/
    buffer.clear();
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String response = new String(bytes);
    System.out.println("Server  responded: " + response);
    client.close();
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    NetworkInterface networkInterface = NetworkInterface.getByName("net1");

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

    dc.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    dc.bind(new InetSocketAddress(8080));
    dc.setOption(StandardSocketOptions.IP_MULTICAST_IF, networkInterface);

    InetAddress group = InetAddress.getByName("180.90.4.12");
    MembershipKey key = dc.join(group, networkInterface);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DatagramChannel server = null;
    server = DatagramChannel.open();
    InetSocketAddress sAddr = new InetSocketAddress("localhost", 8989);
    server.bind(sAddr);
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    while (true) {
        System.out.println("Waiting for a  message  from" + "  a  remote  host at " + sAddr);
        SocketAddress remoteAddr = server.receive(buffer);
        buffer.flip();//from  w w  w. j a va  2  s  . c  o m
        int limits = buffer.limit();
        byte bytes[] = new byte[limits];
        buffer.get(bytes, 0, limits);
        String msg = new String(bytes);

        System.out.println("Client at " + remoteAddr + "  says: " + msg);
        buffer.rewind();
        server.send(buffer, remoteAddr);
        buffer.clear();
    }
    //server.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    MembershipKey key = null;//from   w  w w  . j a v  a2  s  .  co m
    DatagramChannel client = DatagramChannel.open(StandardProtocolFamily.INET);

    NetworkInterface interf = NetworkInterface.getByName(MULTICAST_INTERFACE_NAME);
    client.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    client.bind(new InetSocketAddress(MULTICAST_PORT));
    client.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);

    InetAddress group = InetAddress.getByName(MULTICAST_IP);
    key = client.join(group, interf);

    System.out.println("Joined the   multicast  group:" + key);
    System.out.println("Waiting for a  message  from  the" + "  multicast group....");

    ByteBuffer buffer = ByteBuffer.allocate(1048);
    client.receive(buffer);
    buffer.flip();
    int limits = buffer.limit();
    byte bytes[] = new byte[limits];
    buffer.get(bytes, 0, limits);
    String msg = new String(bytes);

    System.out.format("Multicast Message:%s%n", msg);
    key.drop();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Set<UpnpIgdDevice> scanForDevices(InetSocketAddress multicastSocketAddress,
        Set<InetAddress> localAddresses, String searchQuery) throws IOException, InterruptedException {

    final Set<UpnpIgdDevice> ret = Collections.synchronizedSet(new HashSet<UpnpIgdDevice>());
    final Map<Channel, InetAddress> bindMap = Collections.synchronizedMap(new HashMap<Channel, InetAddress>());

    UdpCommunicatorListener listener = new UdpCommunicatorListener() {

        @Override/*w ww  . ja va 2 s  .  co  m*/
        public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                ByteBuffer packet) {
            byte[] inPacket = ByteBufferUtils.copyContentsToArray(packet);

            String inStr;
            try {
                inStr = new String(inPacket, 0, inPacket.length, "US-ASCII");
            } catch (UnsupportedEncodingException uee) {
                return;
            }

            Matcher matcher;

            URI url;
            if ((matcher = LOCATION_PATTERN.matcher(inStr)).find()) {
                String urlStr = matcher.group(1);
                try {
                    url = new URI(urlStr);
                } catch (URISyntaxException urise) {
                    return;
                }
            } else {
                return;
            }

            String name = null;
            if ((matcher = SERVER_PATTERN.matcher(inStr)).find()) {
                name = matcher.group(1);
            }

            InetAddress localAddress = bindMap.get(channel);

            UpnpIgdDevice device = new UpnpIgdDevice(localAddress, sourceAddress.getAddress(), name, url);
            ret.add(device);
        }
    };

    UdpCommunicator comm = null;
    try {
        List<DatagramChannel> channels = new ArrayList<>();

        for (InetAddress localAddr : localAddresses) {
            DatagramChannel channel = DatagramChannel.open();
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(localAddr, 0));
            channels.add(channel);

            bindMap.put(channel, localAddr);
        }

        comm = new UdpCommunicator(channels);
        comm.startAsync().awaitRunning();
        comm.addListener(listener);

        ByteBuffer searchQueryBuffer = ByteBuffer.wrap(searchQuery.getBytes("US-ASCII")).asReadOnlyBuffer();
        for (int i = 0; i < 3; i++) {
            for (DatagramChannel channel : channels) {
                comm.send(channel, multicastSocketAddress, searchQueryBuffer.asReadOnlyBuffer());
            }

            Thread.sleep(TimeUnit.SECONDS.toMillis(MAX_WAIT + 1));
        }

        return new HashSet<>(ret);
    } finally {
        if (comm != null) {
            try {
                comm.stopAsync().awaitTerminated(); // this stop should handle closing all the datagram channels
            } catch (IllegalStateException ise) { // NOPMD
                // do nothing
            }
        }
    }
}

From source file:org.apache.nifi.io.nio.ChannelListener.java

private DatagramChannel createAndBindDatagramChannel(final InetAddress nicIPAddress, final int port,
        final int receiveBufferSize) throws IOException {
    final DatagramChannel dChannel = DatagramChannel.open();
    dChannel.configureBlocking(false);/*from  w  ww .  ja  v a  2s . c om*/
    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;
}

From source file:org.mobicents.media.server.impl.rtcp.RtcpHandlerTest.java

@Test
public void testRtcpSend() throws IOException, InterruptedException {
    /* GIVEN *///w ww.  ja va 2  s  . c o  m
    SnifferChannel recvChannel = new SnifferChannel();
    recvChannel.open();
    recvChannel.bind(new InetSocketAddress("127.0.0.1", 0));

    DatagramChannel sendChannel = DatagramChannel.open();
    sendChannel.bind(new InetSocketAddress("127.0.0.1", 0));

    recvChannel.connect(sendChannel.getLocalAddress());
    sendChannel.connect(recvChannel.getLocalAddress());

    /* WHEN */
    handler.setChannel(sendChannel);
    handler.joinRtpSession();

    recvChannel.start();
    new Thread(recvChannel).start();
    Thread.sleep(15000);

    handler.leaveRtpSession();
    Thread.sleep(5000);
    recvChannel.stop();

    /* THEN */
    Assert.assertTrue(recvChannel.rxPackets > 0);
    Assert.assertTrue(recvChannel.rxOctets > 0);
    Assert.assertEquals(recvChannel.rxPackets, statistics.getRtcpPacketsSent());
    Assert.assertEquals(recvChannel.rxOctets, statistics.getRtcpOctetsSent());
}