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:gravity.android.discovery.DiscoveryClient.java

public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) {
    ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>();

    try {/*from www . j a  v  a 2  s .  c om*/
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.setBroadcast(true);
        InetAddress IPAddress = Utils.getBroadcastAddress(mWifi);
        Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress());
        byte[] receiveData = new byte[2048];
        byte[] sendData = new byte[128];

        sendData = token.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        Log.v("DISCOVERY_CLIENT", "sent " + token);
        clientSocket.send(sendPacket);

        long t1 = System.currentTimeMillis();
        while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                clientSocket.setSoTimeout(500);
                clientSocket.receive(receivePacket);

                if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) {
                    String discovered_name, discovered_ip;
                    int discovered_port;

                    String received = new String(receivePacket.getData());

                    if (received != null) {
                        received = received.trim().substring(0, receivePacket.getLength()).trim();
                        Log.d("Recieved Msg Packet:", received);

                        //StringTokenizer st = new StringTokenizer(received, ",");

                        //Gravity Code
                        JSONObject recievedJson = new JSONObject(received);

                        try {
                            //discovered_name = st.nextToken();   
                            discovered_name = recievedJson.getString("name"); //Gravity code

                            discovered_ip = receivePacket.getAddress().getHostAddress();

                            //discovered_port = Integer.parseInt(st.nextToken());
                            discovered_port = recievedJson.getInt("port_to_share"); //Gravity code

                            Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip
                                    + ":" + discovered_port);

                            boolean add = true;
                            if (ret.size() > 0) {
                                for (DiscoveryServerInfo dsi : ret) {
                                    if (dsi != null && dsi.ip.equals(discovered_ip)) {
                                        add = false;
                                        break;
                                    }
                                }
                            }

                            if (add) {
                                ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip,
                                        discovered_port));
                            }
                        } catch (NoSuchElementException nsee) {
                            Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage());
                        }

                    }
                }

            } catch (SocketTimeoutException tex) {
                /* ignored */ }
        }

        clientSocket.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("DISCOVERY_CLIENT", ex.toString());
    }

    return ret;
}

From source file:werewolf.client.DatagramReceiverThread.java

/**
 * Send message pake UDP//  www.j  a v a 2 s  .  c o  m
 *
 * @param message JSON Object yang mau dikirim
 * @param address Alamat tujuan
 * @param udpPort Port tujuan
 */
public static void sendUDPMessage(JSONObject message, String address, int udpPort) {
    System.out.println("send: " + message.toString());
    System.out.println("to: " + address + " " + udpPort);

    try {
        InetAddress IPAddress = InetAddress.getByName(address);
        int targetPort = udpPort;

        UnreliableSender unreliableSender = new UnreliableSender(socket);

        byte[] sendData = message.toJSONString().getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, targetPort);
        unreliableSender.send(sendPacket);

    } catch (UnknownHostException ex) {
        Logger.getLogger(WerewolfClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(WerewolfClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:tubessister.SenderR.java

public void run() {
    System.out.println("Sender Running ");
    try {//w w w . j av a  2  s.c  o  m
        InetAddress IPAddress = InetAddress.getByName(targetAddress);
        DatagramSocket datagramSocket = new DatagramSocket();
        ReliableSender ReliableSender = new ReliableSender(datagramSocket);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, targetPort);
        ReliableSender.send(sendPacket);
        datagramSocket.close();
    } catch (UnknownHostException ex) {
        System.out.println("Unknown Host Exception");
    } catch (SocketException ex) {
        System.out.println("Socket  Exception");
    } catch (IOException ex) {
        System.out.println("IO Exception");
    }
    System.out.println("Send finished");
}

From source file:tubessister.Sender.java

public void run() {
    //System.out.println("Sender Running " );
    try {//ww w  . j  a  v  a 2 s.co  m
        InetAddress IPAddress = InetAddress.getByName(targetAddress);
        DatagramSocket datagramSocket = new DatagramSocket();
        UnreliableSender unreliableSender = new UnreliableSender(datagramSocket);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, targetPort);
        unreliableSender.send(sendPacket);
        datagramSocket.close();
    } catch (UnknownHostException ex) {
        System.out.println("Unknown Host Exception");
    } catch (SocketException ex) {
        System.out.println("Socket  Exception");
    } catch (IOException ex) {
        System.out.println("IO Exception");
    }
    System.out.println("Send finished");
}

From source file:werewolf_client.Werewolf_Client.java

public void sentToClient(String adr, int p, String message)
        throws SocketException, UnknownHostException, IOException {
    DatagramSocket sender = new DatagramSocket();
    InetAddress ip = InetAddress.getByName(adr);
    byte[] sendData = new byte[1024];
    sendData = message.getBytes();/*from ww w. j a  v  a2s . com*/

    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, p);
    double rand = random.nextDouble();
    if (rand < 0.85) {
        sender.send(sendPacket);
    }
    sender.close();
}

From source file:org.wso2.esb.integration.common.utils.clients.UDPClient.java

/**
 * Send UDP message/*from w  w w .j  av  a2s  .  c  om*/
 *
 * @param message message
 */
public void sendMessage(String message) throws IOException {
    DatagramSocket clientSocket = null;

    try {
        clientSocket = new DatagramSocket();
        InetAddress inetAddress = InetAddress.getByName(host);
        byte[] sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress, port);
        clientSocket.send(sendPacket);
    } finally {
        if (clientSocket != null) {
            clientSocket.close();
        }
    }
}

From source file:MainClass.java

public void run() {

    try {/*from w w  w. j  a v a2s.  c  o m*/
        BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            if (stopped)
                return;
            String theLine = userInput.readLine();
            if (theLine.equals("."))
                break;
            byte[] data = theLine.getBytes();
            DatagramPacket output = new DatagramPacket(data, data.length, server, port);
            socket.send(output);
            Thread.yield();
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:easy.api.service.ComponentSocket.java

public String send() throws UnknownHostException, SocketException, IOException {
    String result = "";
    // create socket to IP
    final InetAddress inetAddress = InetAddress.getByName(this.ipAddress);
    byte[] base64String = Base64.decodeBase64(this.magicPacketBase64.getBytes());
    //byte[] base64String = Base64.decodeBase64(this.magicPacketBase64);
    DatagramPacket datagramPacket = new DatagramPacket(base64String, base64String.length, inetAddress,
            this.udpPort);
    try (DatagramSocket datagramSocket = new DatagramSocket()) {
        datagramSocket.send(datagramPacket);
        result += this.magicPacketBase64 + " send successfull!!\n";
    } catch (Exception e) {
        result += e.getMessage();/*w ww .j  a v  a2 s  .c o m*/
    }
    return result;
}

From source file:org.openhab.binding.edimax.internal.UDPDiscoverer.java

private EdimaxDevice[] discover() throws SocketException, UnknownHostException, IOException {
    List<EdimaxDevice> discoveredDevices = new ArrayList<EdimaxDevice>();
    DatagramSocket serverSocket = null;
    try {/*from ww w .j ava 2s .  co  m*/
        serverSocket = new DatagramSocket(12346); // choose random port,
        // because with empty
        // port sometimes error
        // occures.

        // send UDP broadcast
        InetAddress ipAddress = InetAddress.getByName("255.255.255.255");
        byte[] sendData = DISCOVERY_BYTES;
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 20560);
        serverSocket.send(sendPacket);

        // receive
        serverSocket.setSoTimeout(1000 * 5);
        byte[] receiveData = new byte[1024];

        try {
            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());

                if (!StringUtils.isEmpty(sentence) && sentence.contains("EDIMAX")) {
                    byte[] mac = new byte[6];
                    System.arraycopy(receivePacket.getData(), 0, mac, 0, 6);

                    String encodedMAC = Hex.encodeHexString(mac).toUpperCase();
                    InetAddress discoveredIp = receivePacket.getAddress();

                    EdimaxDevice dev = new EdimaxDevice();
                    dev.setIp(discoveredIp.getHostAddress());
                    dev.setMac(encodedMAC);

                    discoveredDevices.add(dev);
                }

            }
        } catch (SocketTimeoutException e) {
            // intended to happen
        }
    } finally {
        if (serverSocket != null) {
            serverSocket.close();
        }
    }
    return discoveredDevices.toArray(new EdimaxDevice[discoveredDevices.size()]);
}

From source file:be.error.rpi.adc.ObjectStatusUdpSender.java

public void send(List<Pair<AdcChannel, ObjectStatusType>> results) throws Exception {
    for (Pair<AdcChannel, ObjectStatusType> pair : results) {
        byte id = (byte) Integer.parseInt(pair.getLeft().getId());
        byte[] toSend = add(new byte[] { id }, pair.getRight().getId());
        DatagramPacket sendPacket = new DatagramPacket(toSend, toSend.length, IPAddress, port);
        clientSocket.send(sendPacket);//from  w  w w.j a  v  a 2s .  c om
    }
}