Example usage for java.net DatagramPacket DatagramPacket

List of usage examples for java.net DatagramPacket DatagramPacket

Introduction

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

Prototype

public DatagramPacket(byte buf[], int length) 

Source Link

Document

Constructs a DatagramPacket for receiving packets of length length .

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    final int LOCAL_PORT = 12345;
    final String SERVER_NAME = "localhost";
    DatagramSocket udpSocket = new DatagramSocket(LOCAL_PORT, InetAddress.getByName(SERVER_NAME));

    System.out.println("Created UDP  server socket at " + udpSocket.getLocalSocketAddress() + "...");
    while (true) {
        System.out.println("Waiting for a  UDP  packet...");
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
        udpSocket.receive(packet);//from w ww.j ava2s  .c o  m
        displayPacketDetails(packet);
        udpSocket.send(packet);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int mcPort = 12345;
    String mcIPStr = "230.1.1.1";
    MulticastSocket mcSocket = null;
    InetAddress mcIPAddress = null;
    mcIPAddress = InetAddress.getByName(mcIPStr);
    mcSocket = new MulticastSocket(mcPort);
    System.out.println("Multicast Receiver running at:" + mcSocket.getLocalSocketAddress());
    mcSocket.joinGroup(mcIPAddress);//from  ww  w . ja va 2 s  .c  om

    DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

    System.out.println("Waiting for a  multicast message...");
    mcSocket.receive(packet);
    String msg = new String(packet.getData(), packet.getOffset(), packet.getLength());
    System.out.println("[Multicast  Receiver] Received:" + msg);

    mcSocket.leaveGroup(mcIPAddress);
    mcSocket.close();
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {/*from   w  w w.  j a v a2  s.c o  m*/
        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 {//from  w  w  w  . j  ava 2 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:ChatClient.java

public static void main(String[] args) throws Exception {
        int PORT = 4000;
        byte[] buf = new byte[1000];
        DatagramPacket dgp = new DatagramPacket(buf, buf.length);
        DatagramSocket sk;//from w  w  w  .java2 s . co m

        sk = new DatagramSocket(PORT);
        System.out.println("Server started");
        while (true) {
            sk.receive(dgp);
            String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: " + dgp.getAddress()
                    + ", port: " + dgp.getPort();
            System.out.println(rcvd);

            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            String outMessage = stdin.readLine();
            buf = ("Server say: " + outMessage).getBytes();
            DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort());
            sk.send(out);
        }
    }

From source file:MulticastClient.java

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

   MulticastSocket socket = new MulticastSocket(4446);
   InetAddress address = InetAddress.getByName("230.0.0.1");
   socket.joinGroup(address);//from   ww  w.ja  va2  s .c om

   DatagramPacket packet;

   // get a few quotes
   for (int i = 0; i < 5; i++) {

      byte[] buf = new byte[256];
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      String received = new String(packet.getData());
      System.out.println("Quote of the Moment: " + received);
   }

   socket.leaveGroup(address);
   socket.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;/*from  w  ww .  j  a  va 2  s. c om*/
    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:Main.java

private static DatagramPacket getRequestPacket() {
    String request = "00002";
    byte[] start_request_array = request.getBytes();
    DatagramPacket request_packet = new DatagramPacket(start_request_array, start_request_array.length);
    return request_packet;
}

From source file:Main.java

private static void receive(Map<Integer, byte[]> map, DatagramSocket socket, int[] length) {
    byte[] b = new byte[limit + 4];
    DatagramPacket p = new DatagramPacket(b, b.length);
    try {/*w  w  w . ja  va2 s . c o  m*/
        socket.receive(p);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    if (p.getLength() != 0) {
        ByteBuffer buf = ByteBuffer.wrap(b);
        int key = buf.getInt();
        byte[] bytes = new byte[p.getLength() - 4];
        length[0] += bytes.length;
        buf.get(bytes);
        map.put(key, bytes);
        receive(map, socket, length);
    }
}

From source file:Main.java

public static DatagramPacket getPacket(String msg) throws UnknownHostException {
    int PACKET_MAX_LENGTH = 1024;
    byte[] msgBuffer = msg.getBytes();

    int length = msgBuffer.length;
    if (length > PACKET_MAX_LENGTH) {
        length = PACKET_MAX_LENGTH;/*from  ww w .  ja va  2 s .co  m*/
    }
    DatagramPacket packet = new DatagramPacket(msgBuffer, length);
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    packet.setAddress(serverIPAddress);
    packet.setPort(15900);
    return packet;
}