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, InetAddress address, int port) 

Source Link

Document

Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.

Usage

From source file:DatagramSender.java

public static void main(String args[]) throws Exception {
    InetAddress ia = InetAddress.getByName(args[0]);
    // Obtain destination port
    int port = Integer.parseInt(args[1]);
    // Create a datagram socket
    DatagramSocket ds = new DatagramSocket();
    // Create a datagram packet
    byte buffer[] = args[2].getBytes();
    DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, port);
    ds.send(dp);//from  w  w  w  .  j  av  a2s.co m
}

From source file:UdpEchoClient.java

public static void main(String[] args) {
    InetAddress address;/*from w  ww .  j a v  a2  s .  c o m*/
    try {
        address = InetAddress.getByName(args[0]);
    } catch (UnknownHostException host) {
        System.out.println(host);
        return;
    }
    DatagramPacket pack = new DatagramPacket(testString.getBytes(), testString.length(), address, 7);
    DatagramPacket incoming = new DatagramPacket(new byte[256], 256);
    DatagramSocket sock = null;
    try {
        Calendar start, end;
        sock = new DatagramSocket();
        start = Calendar.getInstance();
        sock.send(pack);
        sock.setSoTimeout(5000);
        sock.receive(incoming);
        end = Calendar.getInstance();
        String reply = new String(incoming.getData());
        reply = reply.substring(0, testString.length());
        if (reply.equals(testString)) {
            System.out.println("Success");
            System.out.println("Time = " + (end.getTime().getTime() - start.getTime().getTime()) + "mS");
        } else
            System.out.println("Reply data did not match");
    } catch (SocketException socke) {
        System.out.println(socke);
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        sock.close();
    }
}

From source file:WriteServer.java

public static void main(String args[]) throws Exception {
    int serverPort = 998;

    int buffer_size = 1024;

    byte buffer[] = new byte[buffer_size];

    DatagramSocket ds = new DatagramSocket(serverPort);
    int pos = 0;/*  w  ww.j  a va  2 s .c om*/
    while (true) {
        int c = System.in.read();
        switch (c) {
        case -1:
            System.out.println("Server Quits.");
            return;
        case '\r':
            break;
        case '\n':
            ds.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(), 999));
            pos = 0;
            break;
        default:
            buffer[pos++] = (byte) c;
        }
    }

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    InetAddress server = InetAddress.getByName("localhost");
    BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket theSocket = new DatagramSocket();
    while (true) {
        String theLine = userInput.readLine();
        if (theLine.equals("."))
            break;
        byte[] data = theLine.getBytes();
        DatagramPacket theOutput = new DatagramPacket(data, data.length, server, 99999);
        theSocket.send(theOutput);// w  w w .ja v  a2 s  .c  o  m
    }

}

From source file:MulticastSender.java

public static void main(String[] args) {

    InetAddress ia = null;/*from ww  w  .  j  ava  2  s. c o  m*/
    int port = 0;
    String characters = "Here's some multicast data\n";
    byte[] data = new byte[characters.length()];

    // read the address from the command line
    try {
        try {
            ia = InetAddress.getByName(args[0]);
        } catch (UnknownHostException e) {
            //ia = InetAddressFactory.newInetAddress(args[0]);
        }
        port = Integer.parseInt(args[1]);
    } catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java MulticastSender MulticastAddress port");
        System.exit(1);
    }

    characters.getBytes(0, characters.length(), data, 0);
    DatagramPacket dp = new DatagramPacket(data, data.length, ia, port);

    try {
        MulticastSocket ms = new MulticastSocket();
        ms.joinGroup(ia);
        for (int i = 1; i < 10; i++) {
            ms.send(dp, (byte) 1);
        }
        ms.leaveGroup(ia);
        ms.close();
    } catch (SocketException se) {
        System.err.println(se);
    } catch (IOException ie) {
        System.err.println(ie);
    }

}

From source file:be.error.rpi.test.UdpTest.java

public static void main(String[] args) throws Exception {
    final InetAddress IPAddress = InetAddress.getByName("192.168.0.10");
    final DatagramSocket clientSocket = new DatagramSocket();

    new Thread() {
        @Override//from   w w w  .j  a  v  a  2  s.c om
        public void run() {
            try {
                while (true) {
                    String s = "0:0:0:";
                    DatagramPacket sendPacket = new DatagramPacket(s.getBytes(), s.getBytes().length, IPAddress,
                            8000);
                    clientSocket.send(sendPacket);
                    Thread.sleep(100);
                }
            } catch (Exception e) {

            }
        }
    }.start();

    new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    String s = "1:1:1:";
                    DatagramPacket sendPacket = new DatagramPacket(s.getBytes(), s.getBytes().length, IPAddress,
                            8000);
                    clientSocket.send(sendPacket);
                    Thread.sleep(100);
                }
            } catch (Exception e) {

            }
        }
    }.start();

}

From source file:UDPSend.java

public static void main(String args[]) {
    try {/*from   w  ww. java  2 s  . co  m*/
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:Main.java

public static void senddatagram(InetAddress target, int port, byte[] outbuf, int len) {

    try {/*  w  w w .  j a  v a 2s.c  o m*/
        DatagramPacket request = new DatagramPacket(outbuf, len, target, port);

        DatagramSocket socket = new DatagramSocket();
        socket.send(request);
    } catch (SocketException e) {
    } catch (IOException e) {
    }

}

From source file:Main.java

public static void sendWoLMagicPacket(final String broadcastIp, final String macAddress) {
    new Thread(new Runnable() {
        @Override/*from  www.j a v  a2  s  .  co m*/
        public void run() {
            try {
                byte[] macBytes = getMacBytes(macAddress);
                byte[] bytes = new byte[6 + 16 * macBytes.length];
                for (int i = 0; i < 6; i++) {
                    bytes[i] = (byte) 0xff;
                }
                for (int i = 6; i < bytes.length; i += macBytes.length) {
                    System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
                }

                InetAddress address = InetAddress.getByName(broadcastIp);
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, 9);
                DatagramSocket socket = new DatagramSocket();
                socket.send(packet);
                socket.close();

                packet = new DatagramPacket(bytes, bytes.length, address, 7);
                socket = new DatagramSocket();
                socket.send(packet);
                socket.close();

                Log.e("WAKE_UP", "Wake-on-LAN packet sent.");
                final String output = getStringFromBytes(bytes);
                Log.i("WAKE_UP", output);
            } catch (Exception e) {
                Log.e("WAKE_UP", "Failed to send Wake-on-LAN packet: " + e);

            }
        }
    }).start();
}

From source file:Main.java

static void sendData(byte[] data) throws IOException {
    Log.d(TAG, "sendData data.len:" + data.length);
    while (true) {

        if (multicastSocket == null) {
            multicastSocket = new MulticastSocket(MULTICAST_PORT);
            Log.d(TAG, "new MulticastSocket()");
        }// www  .  ja va  2s . co m

        //MulticastSocket multicastSocket = new MulticastSocket(MULTICAST_PORT);
        multicastSocket.setLoopbackMode(true);
        InetAddress group;
        DatagramPacket packet;
        for (int i = 0; i < data.length; i++) {
            Log.d(TAG, i + ":" + data[i]);
            group = InetAddress.getByName("239." + i + "." + data[i] + ".254");

            multicastSocket.joinGroup(group);
            packet = new DatagramPacket("".getBytes(), "".getBytes().length, group, MULTICAST_PORT);
            multicastSocket.send(packet);
            multicastSocket.leaveGroup(group);
        }
    }
}