Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

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

Prototype

public DatagramSocket() throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to any available port on the local host machine.

Usage

From source file:net.dv8tion.jda.audio.AudioWebSocket.java

private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) {
    //We will now send a packet to discord to punch a port hole in the NAT wall.
    //This is called UDP hole punching.
    try {/* ww  w.  j a v a 2 s.  com*/
        udpSocket = new DatagramSocket(); //Use UDP, not TCP.

        //Create a byte array of length 70 containing our ssrc.
        ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208
        buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord.

        //Construct our packet to be sent loaded with the byte buffer we store the ssrc in.
        DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address);
        udpSocket.send(discoveryPacket);

        //Discord responds to our packet, returning a packet containing our external ip and the port we connected through.
        DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent.
        udpSocket.setSoTimeout(1000);
        udpSocket.receive(receivedPacket);

        //The byte array returned by discord containing our external ip and the port that we used
        //to connect to discord with.
        byte[] received = receivedPacket.getData();

        //Example string:"   121.83.253.66                                                   "
        //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and
        // the last 2 bytes. Not sure why these exist.  The last 2 bytes are the port. More info below.
        String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces.
        ourIP = ourIP.substring(0, ourIP.length() - 2); //Removes the port that is stuck on the end of this string. (last 2 bytes are the port)
        ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP

        //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short.
        //Furthermore, it is stored in Little Endian instead of normal Big Endian.
        //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order)
        //Then we will need to deal with the fact that the bytes represent an unsigned short.
        //Java cannot deal with unsigned types, so we will have to promote the short to a higher type.
        //Options:  char or int.  I will be doing int because it is just easier to work with.
        byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size.
        portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first
        portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second.
        //We have now effectively converted from Little Endian -> Big Endian by reversing the order.

        //For more information on how this is converting from an unsigned short to an int refer to:
        //http://www.darksleep.com/player/JavaAndUnsignedTypes.html
        int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned.
        int secondByte = (0x000000FF & ((int) portBytes[1])); //

        //Combines the 2 bytes back together.
        int ourPort = (firstByte << 8) | secondByte;

        this.address = address;

        return new InetSocketAddress(ourIP, ourPort);
    } catch (SocketException e) {
        return null;
    } catch (IOException e) {
        LOG.log(e);
        return null;
    }
}

From source file:org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider.java

@Override
public void onStart() {

    //This handles the case when I'm the existing device in the network and receive a "hello" UDP package

    udpAcceptor.setHandler(udpHandler);// w w w .java2  s .  com

    try {
        udpAcceptor.bind(new InetSocketAddress(port));
    } catch (Exception e) {
        Log.e("LanLinkProvider", "Error: Could not bind udp socket");
        e.printStackTrace();
    }

    boolean success = false;
    int tcpPort = port;
    while (!success) {
        try {
            tcpAcceptor.bind(new InetSocketAddress(tcpPort));
            success = true;
        } catch (Exception e) {
            tcpPort++;
        }
    }

    Log.i("LanLinkProvider", "Using tcpPort " + tcpPort);

    //I'm on a new network, let's be polite and introduce myself
    final int finalTcpPort = tcpPort;
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            String deviceListPrefs = PreferenceManager.getDefaultSharedPreferences(context)
                    .getString(KEY_CUSTOM_DEVLIST_PREFERENCE, "");
            ArrayList<String> iplist = new ArrayList<String>();
            if (!deviceListPrefs.isEmpty()) {
                iplist = CustomDevicesActivity.deserializeIpList(deviceListPrefs);
            }
            iplist.add("255.255.255.255");
            for (String ipstr : iplist) {
                try {
                    InetAddress client = InetAddress.getByName(ipstr);
                    NetworkPackage identity = NetworkPackage.createIdentityPackage(context);
                    identity.set("tcpPort", finalTcpPort);
                    byte[] b = identity.serialize().getBytes("UTF-8");
                    DatagramPacket packet = new DatagramPacket(b, b.length, client, port);
                    DatagramSocket socket = new DatagramSocket();
                    socket.setReuseAddress(true);
                    socket.setBroadcast(true);
                    socket.send(packet);
                    //Log.i("LanLinkProvider","Udp identity package sent to address "+packet.getAddress());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("LanLinkProvider",
                            "Sending udp identity package failed. Invalid address? (" + ipstr + ")");
                }
            }

            return null;

        }

    }.execute();

}

From source file:org.openhab.binding.network.internal.utils.NetworkUtils.java

/**
 * iOS devices are in a deep sleep mode, where they only listen to UDP traffic on port 5353 (Bonjour service
 * discovery). A packet on port 5353 will wake up the network stack to respond to ARP pings at least.
 *
 * @throws IOException// w w  w.j a v a 2s  .co m
 */
public void wakeUpIOS(InetAddress address) throws IOException {
    try (DatagramSocket s = new DatagramSocket()) {
        byte[] buffer = new byte[0];
        s.send(new DatagramPacket(buffer, buffer.length, address, 5353));
    } catch (PortUnreachableException ignored) {
        // We ignore the port unreachable error
    }
}

From source file:org.rifidi.edge.adapter.csl.util.CslRfidTagServer.java

void StartInventory() {
    String cmdString;//from  w ww. j  av a 2s . c  om
    int OEMCountryCode, OEMModelCode;
    int ret_val = 0;

    while (true) {

        try {
            synchronized (inventoryStarted) {
                if (inventoryStarted)
                    return;
                else
                    inventoryStarted = true;
            }

            String IPAddress = this.IPAddress;

            // open cport (1516)
            TCPCtrlSocket = new Socket(IPAddress, 1516);
            TCPCtrlOut = new DataOutputStream(TCPCtrlSocket.getOutputStream());
            TCPCtrlIn = new DataInputStream(new BufferedInputStream(TCPCtrlSocket.getInputStream()));
            // open iport (1515)
            TCPDataSocket = new Socket(IPAddress, 1515);
            TCPDataOut = new DataOutputStream(TCPDataSocket.getOutputStream());
            TCPDataIn = new DataInputStream(new BufferedInputStream(TCPDataSocket.getInputStream()));
            // open uport (3041)
            clientSocket = new DatagramSocket();
            String returnString = "";

            // Power up RFID module
            logger.info("Power up RFID module with command 0x80000001");
            returnString = CslRfid_SendCtrlCMD("80000001", 5, 2000);
            logger.info(String.format("Return: %s \n", returnString));
            Thread.sleep(2000);

            ReaderMode mode = checkMode();
            if (mode != ReaderMode.lowLevel) {
                // change to low-level
                setMode(ReaderMode.lowLevel);
                // System.out.println("Could not change reader to low-level mode.  Operation abort");

                // reconnect
                TCPCtrlSocket.close();
                TCPDataSocket.close();
                clientSocket.close();
                Thread.sleep(2000);
                // open cport (1516)
                TCPCtrlSocket = new Socket(IPAddress, 1516);
                TCPCtrlOut = new DataOutputStream(TCPCtrlSocket.getOutputStream());
                TCPCtrlIn = new DataInputStream(new BufferedInputStream(TCPCtrlSocket.getInputStream()));
                // open iport (1515)
                TCPDataSocket = new Socket(IPAddress, 1515);
                TCPDataOut = new DataOutputStream(TCPDataSocket.getOutputStream());
                TCPDataIn = new DataInputStream(new BufferedInputStream(TCPDataSocket.getInputStream()));
                // open uport (3041)
                clientSocket = new DatagramSocket();

                logger.info("Power up RFID module with command 0x80000001");
                returnString = CslRfid_SendCtrlCMD("80000001", 5, 2000);
                logger.info(String.format("Return: %s \n", returnString));
                mode = checkMode();
                if (mode != ReaderMode.lowLevel) {
                    TCPCtrlSocket.close();
                    TCPDataSocket.close();
                    clientSocket.close();
                    Thread.sleep(2000);
                    inventoryStarted = false;
                    return;
                }
                Thread.sleep(2000);
            }

            // Enable TCP Notifications
            logger.info("Enable TCP Notifications with command 0x8000011701");
            returnString = CslRfid_SendCtrlCMD("8000011701", 5, 2000);
            logger.info(String.format("Return: %s \n", returnString));
            Thread.sleep(500);

            // Send Abort command
            clearReadBuffer(TCPDataIn);
            logger.info("Send Abort command 0x4003000000000000");
            returnString = CslRfid_SendDataCMD("4003000000000000", 8, 2000);
            logger.info(String.format("Return: %s \n", returnString));

            this.state = ReaderState.CONNECTED;

            // Select Antenna port 0 ANT_PORT_SEL
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("7001010700000000"));
            logger.info("Send ANT_PORT_SEL command 0x7001010700000000");

            Thread.sleep(5);
            // Select RF power Max up to 30dBm
            clearReadBuffer(TCPDataIn);
            if ((readerPower < 0) || (readerPower > 300))
                ret_val = -11;
            else {
                // TCPDataOut.write(hexStringToByteArray("700106072C010000"));
                cmdString = String.format("70010607%02X%02X0000", readerPower & 0xFF,
                        ((readerPower >> 8) & 0xFF));
                TCPDataOut.write(hexStringToByteArray(cmdString));
                logger.info(String.format("Send RF Power command %s \n", cmdString));
            }

            Thread.sleep(5);
            // Set Dwell Time
            clearReadBuffer(TCPDataIn);
            // dwellTime = 0 for CS203 reader
            cmdString = String.format("70010507%02X%02X%02X%02X", dwellTime & 0xff, (dwellTime >> 8) & 0xff,
                    (dwellTime >> 16) & 0xff, (dwellTime >> 24) & 0xff);
            TCPDataOut.write(hexStringToByteArray(cmdString));
            logger.info(String.format("Send Dwell Time command %s \n", cmdString));

            Thread.sleep(5);
            // Set Inventory Round  (ANT_PORT_INV_CNT)
            clearReadBuffer(TCPDataIn);
            // inventoryRound = 0xffffffff for CS203 reader
            inventoryRound = 0xffffffff;
            cmdString = String.format("70010707%02X%02X%02X%02X", inventoryRound & 0xff,
                    (inventoryRound >> 8) & 0xff, (inventoryRound >> 16) & 0xff, (inventoryRound >> 24) & 0xff);
            TCPDataOut.write(hexStringToByteArray(cmdString));
            logger.info(String.format("Send Inventory Round command %s \n", cmdString));

            Thread.sleep(5);
            // Link Profile
            clearReadBuffer(TCPDataIn);
            if ((link_Profile < 0) || (link_Profile > 4))
                ret_val = -12;
            else {
                // TCPDataOut.write(hexStringToByteArray("7001600b02000000"));
                // link_Profile = 2;        // Link Profile
                cmdString = String.format("7001600b%02X000000", link_Profile & 0xff);
                TCPDataOut.write(hexStringToByteArray(cmdString));
                logger.info(String.format("Send Link Profile 2 command %s \n", cmdString));
            }

            Thread.sleep(5);
            // HST Command
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("700100f019000000"));
            logger.info("HST_CMD command 700100f019000000");

            Thread.sleep(5);
            // QUERY_CFG Command for continuous inventory
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("70010007ffff0000"));
            logger.info("QUERY_CFG (continuous mode) command 70010007ffff0000");

            Thread.sleep(5);
            // Set DynamicQ algorithm (INV_SEL)
            clearReadBuffer(TCPDataIn);
            // TCPDataOut.write(hexStringToByteArray("70010309f7005003"));
            if ((algorithm_Q < 0) || (algorithm_Q > 3))
                ret_val = -14;
            else {
                cmdString = String.format("70010209%02X000000", algorithm_Q & 0xff);
                TCPDataOut.write(hexStringToByteArray(cmdString));
                logger.info(String.format("Send Q Algorithm command %s \n", cmdString));
            }

            Thread.sleep(5);
            // start Q
            clearReadBuffer(TCPDataIn);
            if ((startQ < 0) || (startQ > 15))
                ret_val = -15;
            else {
                cmdString = String.format("70010309F%01X400000", startQ & 0xf);
                TCPDataOut.write(hexStringToByteArray(cmdString));
                logger.info(String.format("Send Start Q command %s \n", cmdString));
            }

            Thread.sleep(5);
            // Send INV_CFG
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("7001010901000000"));
            logger.info("Send INV_CFG command 7001010901000000");

            Thread.sleep(5);
            //---------------------------------------- Read Country code
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("7001000502000000"));
            Thread.sleep(5);
            TCPDataOut.write(hexStringToByteArray("700100f003000000"));
            Thread.sleep(5);
            while (true) {
                if (TCPDataIn.available() != 0) {
                    len = TCPDataIn.read(inData);
                    break;
                }
            }
            OEMCountryCode = inData[28];

            Thread.sleep(5);
            //---------------------------------------- Read Model code
            clearReadBuffer(TCPDataIn);
            TCPDataOut.write(hexStringToByteArray("70010005A4000000"));
            Thread.sleep(5);
            TCPDataOut.write(hexStringToByteArray("700100f003000000"));
            Thread.sleep(5);
            while (true) {
                if (TCPDataIn.available() != 0) {
                    len = TCPDataIn.read(inData);
                    break;
                }
            }
            OEMModelCode = inData[28];

            Thread.sleep(5);
            switch (OEMModelCode) {
            case 0:
                cmdString = String.format("Reader Model: CS101-%d \n", OEMCountryCode);
                break;
            case 1:
                cmdString = String.format("Reader Model: CS203-%d \n", OEMCountryCode);
                break;
            case 3:
                cmdString = String.format("Reader Model: CS468-%d \n", OEMCountryCode);
                break;
            case 5:
                cmdString = String.format("Reader Model: CS468INT-%d \n", OEMCountryCode);
                break;
            case 7:
                cmdString = String.format("Reader Model: CS469-%d \n", OEMCountryCode);
                break;
            default:
                cmdString = String.format("Unidentified reader model \n");
                ret_val = -17;
                break;
            }
            System.out.println(cmdString);

            // sel_Country = "G800";
            int t_index = 0;
            // String cty = CslFreqTab.OEMCountryTable[1];
            if (ret_val == 0) {
                //---------------------------------------------------  Set Frequency Table for the Country Select
                ret_val = VerifySelectCountry(sel_Country, OEMCountryCode);
                if (ret_val == 0) {
                    t_index = Arrays.asList(CslFreqTab.OEMCountryTable).indexOf(sel_Country);

                    int[] t_freqTable = CslFreqTab.countryFreqTable[t_index][0];
                    int t_numCh = CslFreqTab.countryFreqTable[t_index][1][0];
                    int t_freqVal;

                    for (int i = 0; i < t_numCh; i++) {
                        Thread.sleep(5);
                        //---------------------------------------- Read Model code
                        clearReadBuffer(TCPDataIn);
                        cmdString = String.format("7001010C%02X000000", i); // Select Channel
                        TCPDataOut.write(hexStringToByteArray(cmdString));
                        Thread.sleep(5);

                        t_freqVal = swapMSBLSB32bit(t_freqTable[i]);
                        cmdString = String.format("7001030C%08X", t_freqVal); // Set Freq
                        TCPDataOut.write(hexStringToByteArray(cmdString));
                        Thread.sleep(5);
                        TCPDataOut.write(hexStringToByteArray("7001020C01000000")); // Enable Channel
                        Thread.sleep(5);
                    }

                } else {
                    cmdString = String.format("The reader -%d does not support selected country!! \n",
                            OEMCountryCode);
                    System.out.println(cmdString);
                }
            }

            //-----------------------------------------  quit if error value returned
            boolean sentAbortCmd = false;
            if (ret_val < 0) {
                inventoryStarted = false;
                tcpClientStarted = false;
                TCPCtrlSocket.close();
                TCPDataSocket.close();
                clientSocket.close();
                Thread.sleep(1000);
                sentAbortCmd = true;
            } else {
                // Start inventory - send (HST_CMD)
                long timer = System.currentTimeMillis();
                clearReadBuffer(TCPDataIn);
                TCPDataOut.write(hexStringToByteArray("700100f00f000000"));
                logger.info("Start inventory - send (HST_CMD) 700100f00f000000");

                while (true) {
                    if (!inventoryStarted && !sentAbortCmd) {
                        // Send Abort command
                        clearReadBuffer(TCPDataIn);
                        TCPDataOut.write(hexStringToByteArray("4003000000000000"));
                        logger.info("Send Abort command 0x4003000000000000");
                        sentAbortCmd = true;
                    }

                    if (TCPDataIn.available() != 0) {
                        timer = System.currentTimeMillis();
                        len = TCPDataIn.read(inData, 0, 8);

                        if (len < 8)
                            continue;

                        if (byteArrayToHexString(inData, len).startsWith("9898989898989898")) {
                            // clearReadBuffer(TCPDataIn);
                            // date = new Date();
                            // System.out.println(dateFormat.format(date) +
                            // " TCP Notification Received.");
                            continue;
                        }

                        if (byteArrayToHexString(inData, len).startsWith("02000780")) {
                            // clearReadBuffer(TCPDataIn);
                            // /date = new Date();
                            // System.out.println(dateFormat.format(date) +
                            // " Antenna Cycle End Notification Received");
                            continue;
                        }

                        if (byteArrayToHexString(inData, len).startsWith("4003BFFCBFFCBFFC")) {
                            TCPCtrlSocket.close();
                            TCPDataSocket.close();
                            clientSocket.close();
                            date = new Date();
                            logger.info("Abort cmd response received " + byteArrayToHexString(inData, len));
                            Thread.sleep(2000);
                            inventoryStarted = false;
                            break;
                        }

                        // int pkt_ver = (int) inData[0];
                        // int flags = (int) inData[1];
                        int pkt_type = (int) (inData[2] & 0xFF) + ((int) (inData[3] & 0xFF) << 8);
                        int pkt_len = (int) (inData[4] & 0xFF) + ((int) (inData[5] & 0xFF) << 8);
                        int datalen = pkt_len * 4;

                        // wait until the full packet data has come in
                        while (TCPDataIn.available() < datalen) {
                        }
                        // finish reading
                        TCPDataIn.read(inData, 8, datalen);

                        if (pkt_type == 0x8001) {
                            TCPCtrlSocket.close();
                            TCPDataSocket.close();
                            clientSocket.close();
                            this.state = ReaderState.NOT_CONNECTED;
                            date = new Date();
                            logger.info("Command End Packet: " + byteArrayToHexString(inData, len + datalen));
                            Thread.sleep(2000);
                            break;
                        }
                        if (pkt_type == 0x8000) {
                            this.state = ReaderState.BUSY;
                            date = new Date();
                            logger.info(dateFormat.format(date) + " Command Begin Packet: "
                                    + byteArrayToHexString(inData, len + datalen));
                            continue;
                        }
                        if (pkt_type == 0x8005) {
                            date = new Date();
                            // System.out.println(dateFormat.format(date) +
                            // " Inventory Packet: " +
                            // byteArrayToHexString(inData,len+datalen));

                            // logger.info("pkt_type == 0x8005 : " + dateFormat.format(date));    // For Test Only

                            byte[] EPC = new byte[1000];
                            TagInfo tag = new TagInfo();

                            tag.pc = byteArrayToHexString(Arrays.copyOfRange(inData, 20, 22), 2);

                            tag.rssi = (float) (inData[13] * 0.8);
                            tag.antennaPort = inData[18];
                            for (int cnt = 0; cnt < (datalen - 16); cnt++) {
                                EPC[cnt] = inData[22 + cnt];
                            }
                            tag.addr = this.IPAddress;
                            tag.epc = byteArrayToHexString(EPC, datalen - 16);
                            tag.timestamp = System.currentTimeMillis();

                            synchronized (TagBuffer) {
                                if (TagBuffer.size() >= 10000)
                                    TagBuffer.remove();
                                TagBuffer.add(tag);
                            }
                        }

                    } else {
                        if (System.currentTimeMillis() - timer >= 8000) {

                            this.state = ReaderState.NOT_CONNECTED;
                            logger.error("Connection lost.  To be reconnected");
                            logger.error("Close Connections");

                            TCPCtrlSocket.close();
                            TCPDataSocket.close();
                            clientSocket.close();
                            Thread.sleep(2000);
                            inventoryStarted = false;
                            break;
                        }
                    }
                }
            }

            if (sentAbortCmd) {
                // exit thread
                logger.info("Inventory Stopped");
                this.state = ReaderState.NOT_CONNECTED;
                inventoryStarted = false;
                break;
            }
        } catch (UnknownHostException e) {
            System.err.println(e.getMessage());
            inventoryStarted = false;
        } catch (IOException e) {
            System.err.println(e.getMessage());
            inventoryStarted = false;
        } catch (java.lang.InterruptedException e) {
            System.err.println(e.getMessage());
            inventoryStarted = false;
        } catch (java.lang.IndexOutOfBoundsException e) {
            System.err.println(e.getMessage());
            inventoryStarted = false;
        }
    }
}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testUdpEchoServer() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(//from   ww  w .  j a  v a 2  s  .co m
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(UdpConnectorFactory.Builder.builder()
                    .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    String message3 = "quit";
    try {
        DatagramSocket socket = new DatagramSocket();
        SocketAddress address = new InetSocketAddress("localhost", 1111);

        // message 1
        byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address);
        socket.send(packet);
        byte[] response = new byte[50];
        DatagramPacket responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message1, messageRead);

        // message2
        byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address);
        socket.send(packet2);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message2, messageRead);

        // message3
        byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address);
        socket.send(packet3);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals("goodbye", messageRead);

    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:com.clustercontrol.hinemosagent.util.AgentConnectUtil.java

/**
 * [Topic] getTopic?????UDP???//from  w w  w. j  a v  a  2s  .c o  m
 * @param facilityId
 */
private static void awakeAgent(String facilityId) {
    String ipAddress = "";
    Integer port = 24005;
    m_log.debug("awakeAgent facilityId=" + facilityId);
    try {
        NodeInfo info = NodeProperty.getProperty(facilityId);
        ipAddress = info.getAvailableIpAddress();
        port = info.getAgentAwakePort();
    } catch (FacilityNotFound e) {
        m_log.debug(e.getMessage(), e);
        return;
    } catch (Exception e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    if (port < 1 || 65535 < port) {
        m_log.info("awakeAgent : invalid port " + port + "(" + facilityId + ")");
    }
    m_log.debug("awakeAgent ipaddress=" + ipAddress);

    final int BUFSIZE = 1;
    byte[] buf = new byte[BUFSIZE];
    buf[0] = 1;
    InetAddress sAddr;
    try {
        sAddr = InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        return;
    }
    DatagramPacket sendPacket = new DatagramPacket(buf, BUFSIZE, sAddr, port);
    DatagramSocket soc = null;
    try {
        soc = new DatagramSocket();
        soc.send(sendPacket);
    } catch (SocketException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } catch (IOException e) {
        m_log.warn("awakeAgent facilityId=" + facilityId + " " + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
    } finally {
        if (soc != null) {
            soc.close();
        }
    }
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Returns the network address with which the task manager shall announce itself to the job manager. To determine
 * the address this method exchanges packets with the job manager.
 * //w  w  w . j  av  a 2  s .c  om
 * @param jobManagerAddress
 *        the address of the job manager
 * @return the address with which the task manager shall announce itself to the job manager
 * @throws DiscoveryException
 *         thrown if an error occurs during the packet exchange
 */
public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetAddress taskManagerAddress = null;
    DatagramSocket socket = null;

    try {

        socket = new DatagramSocket();
        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber);
            addressRequest.setAddress(jobManagerAddress);
            addressRequest.setPort(discoveryPort);

            LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress());
            socket.send(addressRequest);

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.warn("Timeout wainting for task manager address reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.warn("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != TM_ADDRESS_REPLY_ID) {
                LOG.warn("Received response of unknown type " + packetTypeID + ", discarding...");
                continue;
            }

            taskManagerAddress = extractInetAddress(responsePacket);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(StringUtils.stringifyException(ioe));
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (taskManagerAddress == null) {
        throw new DiscoveryException("Unable to obtain task manager address");
    }

    return taskManagerAddress;
}

From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java

private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) {
    //We will now send a packet to discord to punch a port hole in the NAT wall.
    //This is called UDP hole punching.
    try {/*from www .j  a  v a2 s. co  m*/
        udpSocket = new DatagramSocket(); //Use UDP, not TCP.

        //Create a byte array of length 70 containing our ssrc.
        ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208
        buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord.

        //Construct our packet to be sent loaded with the byte buffer we store the ssrc in.
        DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address);
        udpSocket.send(discoveryPacket);

        //Discord responds to our packet, returning a packet containing our external ip and the port we connected through.
        DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent.
        udpSocket.setSoTimeout(1000);
        udpSocket.receive(receivedPacket);

        //The byte array returned by discord containing our external ip and the port that we used
        //to connect to discord with.
        byte[] received = receivedPacket.getData();

        //Example string:"   121.83.253.66                                                   "
        //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and
        // the last 2 bytes. Not sure why these exist.  The last 2 bytes are the port. More info below.
        String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces.
        ourIP = ourIP.substring(4, ourIP.length() - 2); //Removes the SSRC of the answer package and the port that is stuck on the end of this string. (last 2 bytes are the port)
        ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP

        //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short.
        //Furthermore, it is stored in Little Endian instead of normal Big Endian.
        //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order)
        //Then we will need to deal with the fact that the bytes represent an unsigned short.
        //Java cannot deal with unsigned types, so we will have to promote the short to a higher type.
        //Options:  char or int.  I will be doing int because it is just easier to work with.
        byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size.
        portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first
        portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second.
        //We have now effectively converted from Little Endian -> Big Endian by reversing the order.

        //For more information on how this is converting from an unsigned short to an int refer to:
        //http://www.darksleep.com/player/JavaAndUnsignedTypes.html
        int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned.
        int secondByte = (0x000000FF & ((int) portBytes[1])); //

        //Combines the 2 bytes back together.
        int ourPort = (firstByte << 8) | secondByte;

        this.address = address;

        return new InetSocketAddress(ourIP, ourPort);
    } catch (SocketException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:cycronix.udp2ct.UDP2CT.java

public UDP2CT(String[] arg) {

    int defaultPort = 4445;
    double defaultDT = 0.0;

    // For communicating with UDP server; we send a "keep alive" heartbeat message to this server
    // and will receive UDP packets from this server
    DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes
    InetAddress udpserverIP = null;
    int udpserverPort = -1;
    int heartbeatPeriod_msec = -1;

    // Concatenate all of the CTWriteMode types
    String possibleWriteModes = "";
    for (CTWriteMode wm : CTWriteMode.values()) {
        possibleWriteModes = possibleWriteModes + ", " + wm.name();
    }/*from  ww  w  .  j av  a2 s.c o  m*/
    // Remove ", " from start of string
    possibleWriteModes = possibleWriteModes.substring(2);

    //
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption(Option.builder("o").argName("base output dir").hasArg().desc(
            "Base output directory when writing data to local folder (i.e., CTdata location); default = \""
                    + outLoc + "\".")
            .build());
    options.addOption(Option.builder("session").argName("session name").hasArg()
            .desc("Optional session name; if specified, this name is prefixed to the source path.").build());
    options.addOption(Option.builder("source").argName("CT source name").hasArg().desc(
            "This field doubles as the CloudTurbine source name and the CT/Unity player ID; if not specified, defaults to the model color.")
            .build());
    options.addOption(Option.builder("m").argName("multicast address").hasArg()
            .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build());
    options.addOption(Option.builder("p").argName("UDP port").hasArg()
            .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".")
            .build());
    options.addOption(Option.builder("d").argName("delta-Time").hasArg()
            .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = "
                    + Double.toString(defaultDT) + ".")
            .build());
    options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc(
            "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".")
            .build());
    options.addOption(Option.builder("t").argName("trim-Time").hasArg().desc(
            "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc(
            "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.")
            .build());
    options.addOption(Option.builder("bps").argName("blocks per seg").hasArg()
            .desc("Number of blocks per segment; specify 0 for no segments; default = "
                    + Long.toString(blocksPerSegment) + ".")
            .build());
    options.addOption(Option.builder("mc").argName("model color").hasArg().desc(
            "Color of the Unity model; must be one of: Red, Blue, Green, Yellow; default = " + modelColor + ".")
            .build());
    options.addOption(Option.builder("mt").argName("model type").hasArg().desc(
            "Type of the Unity model; must be one of: Primplane, Ball, Biplane; default = " + modelType + ".")
            .build());
    options.addOption(
            Option.builder("w").argName("write mode").hasArg().desc("Type of CT write connection; one of "
                    + possibleWriteModes + "; default = " + writeMode.name() + ".").build());
    options.addOption(Option.builder("host").argName("host[:port]").hasArg()
            .desc("Host:port when writing to CT via FTP, HTTP, HTTPS.").build());
    options.addOption(Option.builder("u").argName("username,password").hasArg()
            .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build());
    options.addOption("xpack", false,
            "Don't pack blocks of data in the Sensors output source; the default (without this command line flag) is to pack this source.");
    options.addOption("xs", "no_sensors_out", false,
            "Don't save UDP packet details to the \"Sensors\" source.");
    options.addOption("xu", "udp_debug", false, "Enable UDP packet parsing debug output.");
    options.addOption("x", "debug", false, "Enable CloudTurbine debug output.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, arg);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("UDP2CT", options);
        return;
    }

    outLoc = line.getOptionValue("o", outLoc);
    if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) {
        outLoc = outLoc + File.separator;
    }
    // Make sure the base output folder location ends in "CTdata"
    if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) {
        outLoc = outLoc + "CTdata" + File.separator;
    }

    sessionName = line.getOptionValue("session", sessionName);
    if (!sessionName.isEmpty()) {
        if (!sessionName.endsWith("\\") && !sessionName.endsWith("/")) {
            sessionName = sessionName + File.separator;
        }
    }

    multiCast = line.getOptionValue("m", multiCast);

    String portStr = line.getOptionValue("p", Integer.toString(defaultPort));
    int portNum = Integer.parseInt(portStr);

    String sdt = line.getOptionValue("d", Double.toString(defaultDT));
    double dt = Double.parseDouble(sdt);

    autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment)));

    packMode = !line.hasOption("xpack");

    bSavePacketDataToCT = !line.hasOption("no_sensors_out");

    udp_debug = line.hasOption("udp_debug");

    debug = line.hasOption("debug");

    // Type of output connection
    String writeModeStr = line.getOptionValue("w", writeMode.name());
    boolean bMatch = false;
    for (CTWriteMode wm : CTWriteMode.values()) {
        if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) {
            writeMode = wm;
            bMatch = true;
        }
    }
    if (!bMatch) {
        System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of "
                + possibleWriteModes);
        System.exit(0);
    }

    if (writeMode != CTWriteMode.LOCAL) {
        // User must have specified the host
        // If FTP or HTTPS, they may also specify username/password
        serverHost = line.getOptionValue("host", serverHost);
        if (serverHost.isEmpty()) {
            System.err.println(
                    "When using write mode \"" + writeModeStr + "\", you must specify the server host.");
            System.exit(0);
        }
        if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) {
            String userpassStr = line.getOptionValue("u", "");
            if (!userpassStr.isEmpty()) {
                // This string should be comma-delimited username and password
                String[] userpassCSV = userpassStr.split(",");
                if (userpassCSV.length != 2) {
                    System.err.println("When specifying a username and password for write mode \""
                            + writeModeStr + "\", separate the username and password by a comma.");
                    System.exit(0);
                }
                serverUser = userpassCSV[0];
                serverPassword = userpassCSV[1];
            }
        }
    }

    // Parameters when talking to a UDP server
    // Can't specify both "-p" and "-udpserver"
    if (line.hasOption("p") && line.hasOption("udpserver")) {
        System.err.println(
                "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both.");
        System.exit(0);
    }
    if (line.hasOption("udpserver")) {
        String udpserverStr = line.getOptionValue("udpserver");
        // Parse the server,port,period_msec from this string
        String[] udpserverConfigCSV = udpserverStr.split(",");
        if (udpserverConfigCSV.length != 3) {
            System.err.println(
                    "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec");
            System.exit(0);
        }
        try {
            udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]);
        } catch (UnknownHostException e) {
            System.err.println("Error processing the \"-udpserver\" server name:\n" + e);
            System.exit(0);
        }
        try {
            udpserverPort = Integer.parseInt(udpserverConfigCSV[1]);
            if (udpserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]);
            if (heartbeatPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
        // Initialize communication with the UDP server
        try {
            // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes
            clientSocket = new DatagramSocket();
        } catch (SocketException e) {
            System.err.println("Error creating DatagramSocket:\n" + e);
            System.exit(0);
        }
        Timer time = new Timer();
        UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort);
        time.schedule(heartbeatTask, 0, heartbeatPeriod_msec);
    }

    // CT/Unity model parameters
    String modelColorRequest = line.getOptionValue("mc", modelColor);
    modelColor = "";
    for (ModelColor mc : ModelColor.values()) {
        if (mc.name().toLowerCase().equals(modelColorRequest.toLowerCase())) {
            modelColor = mc.name();
        }
    }
    if (modelColor.isEmpty()) {
        System.err.println(
                "Unrecognized model color, \"" + modelColorRequest + "\"; model color must be one of:");
        for (ModelColor mc : ModelColor.values()) {
            System.err.println("\t" + mc.name());
        }
        System.exit(0);
    }
    String modelTypeRequest = line.getOptionValue("mt", modelType);
    modelType = "";
    for (ModelType mt : ModelType.values()) {
        if (mt.name().toLowerCase().equals(modelTypeRequest.toLowerCase())) {
            modelType = mt.name();
        }
    }
    if (modelType.isEmpty()) {
        System.err.println("Unrecognized model type, \"" + modelTypeRequest + "\"; model type must be one of:");
        for (ModelType mt : ModelType.values()) {
            System.err.println("\t" + mt.name());
        }
        System.exit(0);
    }

    // Set playerName (source name)
    // Need to set this after setting model color, becasue if the user hasn't
    // set the source name then we default to what they specified for modelColor.
    playerName = line.getOptionValue("source", modelColor);

    //
    // setup 2 instances of CTwriter:
    // 1. ctgamew:   this source will only contain the "CTstates.json" output channel, used by
    //               the CT/Unity game; since this source is a text channel, we don't want this source to be packed
    // 2. ctsensorw: output source for data unpacked from the captured UDP packetes; it is up to the parser class
    //               being employed as to what channels are written to this source
    //
    autoFlushMillis = (long) (autoFlush * 1000.);
    System.err.println("Model: " + modelType);
    // If sessionName isn't blank, it will end in a file separator
    String srcName = sessionName + "GamePlay" + File.separator + playerName;
    System.err.println("Game source: " + srcName);
    // NB, 2018-09-27: force bPack false for the GamePlay source;
    //                 this source will only contain a String channel,
    //                 and as of right now CT *will* pack String
    //                 channels (but we don't want this channel packed)
    ctgamew = createCTwriter(srcName, false);
    if (!bSavePacketDataToCT) {
        System.err.println("Sensor data will not be written out");
    } else {
        // If sessionName isn't blank, it will end in a file separator
        srcName = sessionName + "Sensors" + File.separator + playerName;
        System.err.println("Sensor data source: " + srcName);
        ctsensorw = createCTwriter(srcName, packMode);
    }

    //
    // Start UDPread
    //
    if (clientSocket != null) {
        System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort);
        new UDPread(this, clientSocket, dt).start();
    } else {
        System.err.println("Capture UDP packets on port: " + portNum);
        new UDPread(this, portNum, dt).start();
    }
}