Example usage for java.nio.channels DatagramChannel socket

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

Introduction

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

Prototype

public abstract DatagramSocket socket();

Source Link

Document

Retrieves a datagram socket associated with this channel.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    DatagramChannel channel = DatagramChannel.open();
    DatagramSocket socket = channel.socket();
    SocketAddress address = new InetSocketAddress(9999);
    socket.bind(address);// w w w  . ja  v a 2 s .  com
    ByteBuffer buffer = ByteBuffer.allocateDirect(65507);
    while (true) {
        SocketAddress client = channel.receive(buffer);
        buffer.flip();
        channel.send(buffer, client);
        buffer.clear();
    }
}

From source file:UDPTimeServer.java

public static void main(String[] args) throws IOException {

    int port = 37;

    ByteBuffer in = ByteBuffer.allocate(8192);
    ByteBuffer out = ByteBuffer.allocate(8);
    out.order(ByteOrder.BIG_ENDIAN);
    SocketAddress address = new InetSocketAddress(port);
    DatagramChannel channel = DatagramChannel.open();
    DatagramSocket socket = channel.socket();
    socket.bind(address);//ww  w. j a  v a2s. c  o  m
    System.err.println("bound to " + address);
    while (true) {
        try {
            in.clear();
            SocketAddress client = channel.receive(in);
            System.err.println(client);
            long secondsSince1970 = System.currentTimeMillis();
            out.clear();
            out.putLong(secondsSince1970);
            out.flip();

            out.position(4);
            channel.send(out, client);
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    DatagramChannel channel = DatagramChannel.open();
    SocketAddress address = new InetSocketAddress(0);
    DatagramSocket socket = channel.socket();
    socket.bind(address);/*from  ww w.j  a v a 2 s  . c o  m*/

    SocketAddress server = new InetSocketAddress("time-a.nist.gov", 37);
    channel.connect(server);

    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.BIG_ENDIAN);
    // send a byte of data to the server
    buffer.put((byte) 0);
    buffer.flip();
    channel.write(buffer);

    // get the buffer ready to receive data
    buffer.clear();
    // fill the first four bytes with zeros
    buffer.putInt(0);
    channel.read(buffer);
    buffer.flip();

    // convert seconds since 1900 to a java.util.Date
    long secondsSince1900 = buffer.getLong();
    long differenceBetweenEpochs = 2208988800L;
    long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
    long msSince1970 = secondsSince1970 * 1000;
    Date time = new Date(msSince1970);

    System.out.println(time);
}

From source file:UDPTimeClient.java

public static void main(String[] args) throws Exception {

    DatagramChannel channel = DatagramChannel.open();
    // port 0 selects any available port
    SocketAddress address = new InetSocketAddress(0);
    DatagramSocket socket = channel.socket();
    socket.setSoTimeout(5000);/*w  ww . j  av  a 2 s  .  c o m*/
    socket.bind(address);

    SocketAddress server = new InetSocketAddress("time.nist.gov", 37);
    ByteBuffer buffer = ByteBuffer.allocate(8192);
    // time protocol always uses big-endian order
    buffer.order(ByteOrder.BIG_ENDIAN);
    // Must put at least one byte of data in the buffer;
    // it doesn't matter what it is.
    buffer.put((byte) 65);
    buffer.flip();

    channel.send(buffer, server);

    buffer.clear();
    buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 0);
    channel.receive(buffer);
    buffer.flip();
    long secondsSince1970 = buffer.getLong();

    System.out.println(secondsSince1970);
    channel.close();

}

From source file:DaytimeServer.java

public static void main(String args[]) {
    try { // Handle startup exceptions at the end of this block
        // Get an encoder for converting strings to bytes
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

        // Allow an alternative port for testing with non-root accounts
        int port = 13; // RFC867 specifies this port.
        if (args.length > 0)
            port = Integer.parseInt(args[0]);

        // The port we'll listen on
        SocketAddress localport = new InetSocketAddress(port);

        // Create and bind a tcp channel to listen for connections on.
        ServerSocketChannel tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localport);

        // Also create and bind a DatagramChannel to listen on.
        DatagramChannel udpserver = DatagramChannel.open();
        udpserver.socket().bind(localport);

        // Specify non-blocking mode for both channels, since our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        // Register the channels with the selector, and specify what
        // conditions (a connection ready to accept, a datagram ready
        // to read) we'd like the Selector to wake up for.
        // These methods return SelectionKey objects, which we don't
        // need to retain in this example.
        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        // This is an empty byte buffer to receive emtpy datagrams with.
        // If a datagram overflows the receive buffer size, the extra bytes
        // are automatically discarded, so we don't have to worry about
        // buffer overflow attacks here.
        ByteBuffer receiveBuffer = ByteBuffer.allocate(0);

        // Now loop forever, processing client connections
        for (;;) {
            try { // Handle per-connection problems below
                // Wait for a client to connect
                selector.select();//from w  w w  .j ava  2 s  . c  om

                // If we get here, a client has probably connected, so
                // put our response into a ByteBuffer.
                String date = new java.util.Date().toString() + "\r\n";
                ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

                // Get the SelectionKey objects for the channels that have
                // activity on them. These are the keys returned by the
                // register() methods above. They are returned in a
                // java.util.Set.
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    // Get a key from the set, and remove it from the set
                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    // Get the channel associated with the key
                    Channel c = (Channel) key.channel();

                    // Now test the key and the channel to find out
                    // whether something happend on the TCP or UDP channel
                    if (key.isAcceptable() && c == tcpserver) {
                        // A client has attempted to connect via TCP.
                        // Accept the connection now.
                        SocketChannel client = tcpserver.accept();
                        // If we accepted the connection successfully,
                        // the send our respone back to the client.
                        if (client != null) {
                            client.write(response); // send respone
                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {
                        // A UDP datagram is waiting. Receive it now,
                        // noting the address it was sent from.
                        SocketAddress clientAddress = udpserver.receive(receiveBuffer);
                        // If we got the datagram successfully, send
                        // the date and time in a response packet.
                        if (clientAddress != null)
                            udpserver.send(response, clientAddress);
                    }
                }
            } catch (java.io.IOException e) {
                // This is a (hopefully transient) problem with a single
                // connection: we log the error, but continue running.
                // We use our classname for the logger so that a sysadmin
                // can configure logging for this server independently
                // of other programs.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.WARNING, "IOException in DaytimeServer", e);
            } catch (Throwable t) {
                // If anything else goes wrong (out of memory, for example)
                // then log the problem and exit.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.SEVERE, "FATAL error in DaytimeServer", t);
                System.exit(1);
            }
        }
    } catch (Exception e) {
        // This is a startup error: there is no need to log it;
        // just print a message and exit
        System.err.println(e);
        System.exit(1);
    }
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException {
    final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>());
    Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351

    DatagramChannel unicastChannel = null;
    try {//from ww  w  .j  a v a  2 s .c  o m
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(Collections.singletonList(unicastChannel));
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (InetAddress potentialGateway : potentialGateways) {
            communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351),
                    outBuf.asReadOnlyBuffer());
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashSet<>(foundGateways);
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException {
    final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>());
    Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351

    DatagramChannel unicastChannel = null;
    try {//from  w w w.  ja va2  s  . co  m
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(Collections.singletonList(unicastChannel));
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(1100);
        MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"),
                0L);
        mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this
                                                                 // should be fine because all we're looking for is a response, not
                                                                 // nessecarily a correct response -- self address being sent is
                                                                 // 0.0.0.0 (IPV4)
                                                                 //
                                                                 // also, we need to pass in MAP because Apple's garbage routers
                                                                 // give back NATPMP responses when you pass in ANNOUNCE

        outBuf.flip();

        for (InetAddress potentialGateway : potentialGateways) {
            communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351),
                    outBuf.asReadOnlyBuffer());
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses
    return new HashSet<>(foundGateways);
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {//from  ww  w  .  ja  va2  s  .  co m
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {/*from w  ww.  j a  v  a 2  s .  c o m*/
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go
                if (packet.remaining() < 4
                        || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) {
                    return;
                }

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                ByteBuffer outBuf = ByteBuffer.allocate(1100);
                MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0,
                        InetAddress.getByName("::"), 0L);
                mpr.dump(outBuf, bindMap.get(channel));
                outBuf.flip();

                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:gridool.util.net.PoolableSocketChannelFactory.java

private static DatagramChannel createDatagramChannel(final SocketAddress sockAddr, final boolean blocking) {
    final DatagramChannel ch;
    try {/*from  w ww  .  j av a2s.  co m*/
        ch = DatagramChannel.open();
        ch.configureBlocking(blocking);
    } catch (IOException e) {
        LOG.error("Failed to open DatagramChannel.", e);
        throw new IllegalStateException(e);
    }
    try {
        ch.socket().setBroadcast(false);
    } catch (SocketException e) {
        LOG.error("Failed to configure socket.", e);
        throw new IllegalStateException(e);
    }
    try {
        ch.connect(sockAddr);
    } catch (IOException e) {
        LOG.error("Failed to connect socket: " + sockAddr, e);
        throw new IllegalStateException(e);
    }
    return ch;
}