Example usage for java.net DatagramPacket setLength

List of usage examples for java.net DatagramPacket setLength

Introduction

In this page you can find the example usage for java.net DatagramPacket setLength.

Prototype

public synchronized void setLength(int length) 

Source Link

Document

Set the length for this packet.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {/*  ww w.  j a v  a2  s .co m*/

        int port = 80;

        DatagramSocket ds = new DatagramSocket(port);

        byte buffer[] = new byte[BUFSIZE];

        while (true) {

            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            // Receive data
            ds.receive(dp);

            dp.setLength(10);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:DaytimeClient.java

public static void main(String args[]) throws java.io.IOException {
    // Figure out the host and port we're going to talk to
    String host = args[0];//from   w  ww .  j av  a2  s .  c om
    int port = 13;
    if (args.length > 1)
        port = Integer.parseInt(args[1]);

    // Create a socket to use
    DatagramSocket socket = new DatagramSocket();

    // Specify a 1-second timeout so that receive() does not block forever.
    socket.setSoTimeout(1000);

    // This buffer will hold the response. On overflow, extra bytes are
    // discarded: there is no possibility of a buffer overflow attack here.
    byte[] buffer = new byte[512];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port));

    // Try three times before giving up
    for (int i = 0; i < 3; i++) {
        try {
            // Send an empty datagram to the specified host (and port)
            packet.setLength(0); // make the packet empty
            socket.send(packet); // send it out

            // Wait for a response (or timeout after 1 second)
            packet.setLength(buffer.length); // make room for the response
            socket.receive(packet); // wait for the response

            // Decode and print the response
            System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII"));
            // We were successful so break out of the retry loop
            break;
        } catch (SocketTimeoutException e) {
            // If the receive call timed out, print error and retry
            System.out.println("No response");
        }
    }

    // We're done with the channel now
    socket.close();
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {// w ww.  j av a 2 s . com
        int port = 90;

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If a
        // packet is larger than this buffer, the
        // excess will simply be discarded!
        byte[] buffer = new byte[2048];

        // Create a packet to receive data into the buffer
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Now loop forever, waiting to receive packets and printing them.
        while (true) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Convert the contents to a string, and display them
            String msg = new String(buffer, 0, packet.getLength());
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {//  w  ww. ja v a2 s  .c o m
        if (args.length != 1)
            throw new IllegalArgumentException("Wrong number of args");

        // Get the port from the command line
        int port = Integer.parseInt(args[0]);

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If anyone sends us a
        // packet containing more than will fit into this buffer, the
        // excess will simply be discarded!
        byte[] buffer = new byte[2048];

        // Create a packet to receive data into the buffer
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Now loop forever, waiting to receive packets and printing them.
        for (;;) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Decode the bytes of the packet to characters, using the
            // UTF-8 encoding, and then display those characters.
            String msg = new String(buffer, 0, packet.getLength(), "UTF-8");
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            // Prior to Java 1.1, we'd just create a new packet each time.
            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:com.webobjects.monitor.application.HostsPage.java

private boolean hostMeetsMinimumVersion(InetAddress anAddress) {
    byte[] versionRequest;

    try {//from  w w w  . jav a  2 s . c om
        versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException uee) {
        versionRequest = ("womp://queryVersion").getBytes();
    }
    DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress,
            WOApplication.application().lifebeatDestinationPort());

    byte[] mbuffer = new byte[1000];
    DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length);
    DatagramSocket socket = null;

    try {
        socket = new DatagramSocket();
        socket.send(outgoingPacket);
        incomingPacket.setLength(mbuffer.length);
        socket.setSoTimeout(2000);
        socket.receive(incomingPacket);
        String reply = new String(incomingPacket.getData());
        if (reply.startsWith("womp://replyVersion/")) {
            int lastIndex = reply.lastIndexOf(":webObjects");
            lastIndex += 11;
            String version = reply.substring(lastIndex);
            if (version.equals("4.5")) {
                return false;
            }
        } else {
            return false;
        }
    } catch (InterruptedIOException iioe) {
        return true;
    } catch (SocketException se) {
        return true;
    } catch (Throwable e) {
        return false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    return true;
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveUDP(InetSocketAddress address) {
    try {//from ww w.  j a v  a  2  s.  com
        final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        final short udpLength = 512;
        final byte[] in = new byte[udpLength];
        final DatagramPacket indp = new DatagramPacket(in, in.length);
        DatagramPacket outdp = null;
        while (!currentThread().isInterrupted()) {
            indp.setLength(in.length);
            receive(sock, indp);
            final Message query;
            byte[] response;
            try {
                query = new Message(in);
                response = generateReply(query, in, indp.getLength(), null);
                if (response == null) {
                    continue;
                }
            } catch (final IOException ignored) {
                response = formerrMessage(in);
            }
            if (outdp == null) {
                outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());
            } else {
                outdp.setData(response);
                outdp.setLength(response.length);
                outdp.setAddress(indp.getAddress());
                outdp.setPort(indp.getPort());
            }
            sock.send(outdp);
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPAckPacket.java

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>/*ww  w  .  j av  a  2  s.c  om*/
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_blockNumber & 0xffff) >> 8);
    data[3] = (byte) (_blockNumber & 0xff);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(4);

    return datagram;
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPDataPacket.java

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>//ww  w  .  ja  v  a2 s . c  om
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_blockNumber & 0xffff) >> 8);
    data[3] = (byte) (_blockNumber & 0xff);

    // Doublecheck we're not the same
    if (data != _data)
        System.arraycopy(_data, _offset, data, 4, _length);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(_length + 4);

    return datagram;
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPErrorPacket.java

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>/*from   w  w w  .  ja v a 2  s. co  m*/
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    int length;

    length = _message.length();

    data[0] = 0;
    data[1] = (byte) _type;
    data[2] = (byte) ((_error & 0xffff) >> 8);
    data[3] = (byte) (_error & 0xff);

    System.arraycopy(_message.getBytes(), 0, data, 4, length);

    data[length + 4] = 0;

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(length + 4);

    return datagram;
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPRequestPacket.java

/***
 * This is a method only available within the package for
 * implementing efficient datagram transport by elminating buffering.
 * It takes a datagram as an argument, and a byte buffer in which
 * to store the raw datagram data.  Inside the method, the data
 * is set as the datagram's data and the datagram returned.
 * <p>//  ww w . jav a2s. c o  m
 * @param datagram  The datagram to create.
 * @param data The buffer to store the packet and to use in the datagram.
 * @return The datagram argument.
 ***/
final DatagramPacket _newDatagram(DatagramPacket datagram, byte[] data) {
    int fileLength, modeLength;

    fileLength = _filename.length();
    modeLength = _modeBytes[_mode].length;

    data[0] = 0;
    data[1] = (byte) _type;
    System.arraycopy(_filename.getBytes(), 0, data, 2, fileLength);
    data[fileLength + 2] = 0;
    System.arraycopy(_modeBytes[_mode], 0, data, fileLength + 3, modeLength);

    datagram.setAddress(_address);
    datagram.setPort(_port);
    datagram.setData(data);
    datagram.setLength(fileLength + modeLength + 3);

    return datagram;
}