Example usage for java.nio.channels DatagramChannel receive

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

Introduction

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

Prototype

public abstract SocketAddress receive(ByteBuffer dst) throws IOException;

Source Link

Document

Receives a datagram via 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);/*from  w w w  .  java  2s  . c  o m*/
    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  . ja  va 2s .com
    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:Main.java

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

    client.bind(null);//from   w w w.  j  a  v  a  2 s.c  om

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

    client.send(buffer, serverAddress);
    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: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);/*from  w  ww .  ja v  a2 s .com*/
    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();
        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  ww  .  j a va  2 s  . c o  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: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);//ww w  .  j  av a2s.c om
    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  www  . j  a va 2s .co m*/

                // 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:me.schiz.jmeter.ring.udp.EventLoopRunnable.java

private void readCallback(DatagramChannel dc) throws IOException {
    Token t = ring.get(dc);//from www  .  j  a  va  2  s  .com
    t.lock.lock();
    try {
        t.remote = dc.receive(byteBuffer);
        //EOF
        if (t != null) {
            if (t.timeout != null)
                t.timeout.cancel();
        }
        byteBuffer.flip();
        if (t.sampleResult != null) {
            t.sampleResult.sampleEnd();
            byte[] res = Charset.defaultCharset().decode(byteBuffer).toString().getBytes();
            if (t.ishex) {
                t.sampleResult.setResponseData(String.valueOf(Hex.encodeHex(res, true)).getBytes());
            } else {
                t.sampleResult.setResponseData(res);
            }

            while (!t.queue.offer(t.sampleResult)) {
            }
            t.sampleResult = null;
            t.queue = null;
        } else {
            log.warn("have response without request");
        }
        ring.release(t.id);
    } catch (IOException e) {
        t.sampleResult.setResponseCode(e.toString());
        t.sampleResult.setSuccessful(false);
        while (!t.queue.offer(t.sampleResult)) {
        }
    } finally {
        t.lock.unlock();
        byteBuffer.clear();
    }
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected void run() throws Exception {
    ByteBuffer recvBuffer = ByteBuffer.allocate(1100);

    while (true) {
        selector.select();/*from w w  w  .java 2 s.  c om*/
        if (stopFlag) {
            return;
        }

        for (DatagramChannel channel : sendQueue.keySet()) {
            if (!sendQueue.get(channel).isEmpty()) {
                channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            } else {
                channel.register(selector, SelectionKey.OP_READ);
            }
        }

        for (SelectionKey key : selector.selectedKeys()) {
            if (!key.isValid()) {
                continue;
            }

            DatagramChannel channel = (DatagramChannel) key.channel();

            if (key.isReadable()) {
                recvBuffer.clear();
                InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer);
                recvBuffer.flip();
                for (UdpCommunicatorListener listener : listeners) {
                    try {
                        listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            } else if (key.isWritable()) {
                LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue
                        .get(channel);
                ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll();

                if (next != null) {
                    try {
                        channel.send(next.getValue(), next.getKey());
                    } catch (RuntimeException re) { // NOPMD
                        // do nothing
                    }
                }
            }
        }
    }
}

From source file:org.apache.axis2.transport.udp.IODispatcher.java

private void receive(Endpoint endpoint, DatagramChannel channel) {
    try {/*from w w  w  . ja v  a2  s . co m*/
        byte[] data = new byte[endpoint.getMaxPacketSize()];
        ByteBuffer buffer = ByteBuffer.wrap(data);
        InetSocketAddress address = (InetSocketAddress) channel.receive(buffer);
        int length = buffer.position();
        if (log.isDebugEnabled()) {
            log.debug("Received packet from " + address + " with length " + length);
        }
        callback.receive(endpoint, data, length, new UDPOutTransportInfo(address));
    } catch (IOException ex) {
        endpoint.getMetrics().incrementFaultsReceiving();
        log.error("Error receiving UDP packet", ex);
    }
}