Example usage for java.net DatagramPacket setData

List of usage examples for java.net DatagramPacket setData

Introduction

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

Prototype

public synchronized void setData(byte[] buf) 

Source Link

Document

Set the data buffer for this packet.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {/*from  www.j av a2  s .c o 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);
            // Display address from the datagram packet
            InetAddress ia = dp.getAddress();
            System.out.println(ia);

            dp.setData(buffer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);

    // read//w ww.j  ava  2 s .  c  o  m
    DatagramSocket sock = new DatagramSocket(1111);
    sock.receive(pack);
    String word = new String(pack.getData());
    System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
    System.out.println(word);
    sock.close();
    // write
    sock = new DatagramSocket();
    pack.setAddress(InetAddress.getByName(args[1]));
    pack.setData(args[2].getBytes());
    pack.setPort(1111);
    sock.send(pack);
    sock.close();

}

From source file:UDP0.java

public static void main(String[] args) throws Exception {
    byte[] ary = new byte[128];
    DatagramPacket pack = new DatagramPacket(ary, 128);
    if (args[0].charAt(0) == 'r') {
        // read// w w  w  .ja  v a  2  s  .  c om
        DatagramSocket sock = new DatagramSocket(1111);
        sock.receive(pack);
        String word = new String(pack.getData());
        System.out.println("From: " + pack.getAddress() + " Port: " + pack.getPort());
        System.out.println(word);
        sock.close();
    } else { // write
        DatagramSocket sock = new DatagramSocket();
        pack.setAddress(InetAddress.getByName(args[1]));
        pack.setData(args[2].getBytes());
        pack.setPort(1111);
        sock.send(pack);
        sock.close();
    }
}

From source file:SDRecord.java

public static void main(String[] args) {

    boolean recordToInf = false;
    long recordTo = 0, txsize = 0, wr = 0, max = 0;
    int sourcePort = 0, destPort = 0;
    String val;
    OutputStream writer = null;// w ww  .ja  v  a  2s.co  m
    InetAddress rhost = null, lhost = null;
    DatagramSocket socket = null;

    //Default values
    int buffSize = 1500;
    try {
        lhost = InetAddress.getByName("0.0.0.0");
    } catch (UnknownHostException e1) {
        System.err.println("ERROR!: Host not reconized");
        System.exit(3);
    }
    recordToInf = true;
    sourcePort = 7355;

    Options options = new Options();

    options.addOption("m", true, "Minutes to record, default is no limit");
    options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0");
    options.addOption("p", true, "Local port to use, default is 7355");
    options.addOption("r", true, "Remote address where to send data");
    options.addOption("d", true, "Remote port, to use with -r option");
    options.addOption("f", true, "Output file where to save the recording");
    options.addOption("s", true, "Stop recording when reaching specified MBs");
    options.addOption("h", false, "Help");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println("ERROR!: Error while parsing the command line");
        System.exit(1);
    }

    if (cmd.hasOption("m")) {
        val = cmd.getOptionValue("m");
        try {
            if (Long.parseLong(val) < 0) {
                System.err.println("ERROR!: -m argument value cannot be negative");
                System.exit(3);
            }
            recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000);
            recordToInf = false;
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -m argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("l")) {
        val = cmd.getOptionValue("l");
        try {
            lhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("p")) {
        val = cmd.getOptionValue("p");
        try {
            sourcePort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -p argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("r")) {
        val = cmd.getOptionValue("r");
        try {
            rhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("d")) {
        val = cmd.getOptionValue("d");
        try {
            destPort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("-ERROR!: -d argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("f")) {
        val = cmd.getOptionValue("f");
        try {
            writer = new FileOutputStream(val);
        } catch (FileNotFoundException e) {
            System.err.println("ERROR!: File not found");
            System.exit(3);
        }
    }

    if (cmd.hasOption("s")) {
        val = cmd.getOptionValue("s");

        try {
            max = (long) (Double.parseDouble(val) * 1000000);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -s argument not valid");
            System.exit(3);
        }

        if (Double.parseDouble(val) < 0) {
            System.err.println("ERROR!: -s argument value cannot be negative");
            System.exit(3);
        }

    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SDRecord", options);
        System.exit(0);
    }

    try {
        socket = new DatagramSocket(sourcePort, lhost);
        //socket options
        socket.setReuseAddress(true);
    } catch (SocketException e) {
        e.printStackTrace();
        System.exit(3);
    }

    byte[] buffer = new byte[buffSize];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    System.err.println("Listening " + lhost.toString() + " on port " + sourcePort);

    while (recordToInf == true || System.currentTimeMillis() <= recordTo) {
        //Stop recording when reaching max bytes
        if (max != 0 && txsize >= max)
            break;

        packet.setData(buffer);
        try {
            socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(4);
        }

        //Ignoring packets with no data
        if (basicFilter(packet) == null)
            continue;

        if (writer == null && rhost == null)
            wr = recordToStdout(packet);
        if (writer != null)
            wr = recordToFile(packet, writer);
        if (rhost != null)
            wr = recordToSocket(packet, socket, rhost, destPort);

        txsize += wr;
        System.err
                .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate");
    }
    //closing socket and exit
    System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K");
    socket.close();
    System.out.println();
    System.exit(0);
}

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

public void serveUDP(InetSocketAddress address) {
    try {//from   w w  w  .  j  a v  a2 s . c om
        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>/*from   ww w. ja v  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>/*w ww. j  a v  a 2s.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.
 ***/
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 .j  av a 2  s  . 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.
 ***/
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>//from   w  ww.j a v a  2s . 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;
}

From source file:org.lwes.listener.DatagramEnqueuer.java

/**
 * While running, repeatedly read datagrams and insert them into the queue along with the
 * receipt time and other metadata./*from w w w.ja  v a2s. co m*/
 */
@Override
public void run() {
    running = true;

    while (running) {
        try {
            DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
            socket.receive(datagram);
            if (log.isTraceEnabled()) {
                log.trace("Received datagram: " + datagram);
            }
            /* we record the time *after* the receive because it blocks */
            long receiptTime = System.currentTimeMillis();

            /* copy the data into a tight buffer so we can release the loose buffer */
            final byte[] tightBuffer = new byte[datagram.getLength()];
            System.arraycopy(datagram.getData(), 0, tightBuffer, 0, tightBuffer.length);
            datagram.setData(tightBuffer);

            /* create an element for the queue */
            DatagramQueueElement element = new DatagramQueueElement();
            element.setPacket(datagram);
            element.setTimestamp(receiptTime);

            /* add the element to the queue and notify everyone there's work to do */
            queue.put(element);
            if (log.isTraceEnabled()) {
                log.trace("Enqueued: " + element);
            }
        } catch (Exception e) {
            log.warn("Unable to read datagram", e);
        }
    }
}