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:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Attempts to discover peer clusters using Multicast
 * Discovery. Each discovered Cluster will be notified
 * to the {@code PeerClusterService} of the 
 * ClusterManager.//from   w  w w  .j  a  va 2 s  . c om
 * 
 * @throws IOException if occurred during process
 */
public static void discoverPeerClusters() throws IOException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    log.info("[MulticastDiscovery] Discovering Peer Clusters...");

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Response Socket
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Set Socket Timeout
    resSock.setSoTimeout((int) TIMEOUT);

    try {

        // Loop until Socket Timeout Occurs
        while (true) {

            // Receive
            resSock.receive(response);
            processPeerResponse(response.getData());

        }

    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    } finally {
        log.info("[MulticastDiscovery] Peer Cluster Discovery Complete");
    }

}

From source file:org.openhab.binding.tacmi.internal.TACmiBinding.java

/**
 * @throws UnknownHostException//from w w w . j  av  a2  s .  c om
 * @{inheritDoc
 */
@Override
protected void internalReceiveCommand(String itemName, Command command) {
    logger.debug("internalReceiveCommand({},{}) is called!", itemName, command);
    for (TACmiBindingProvider provider : providers) {
        int canNode = provider.getCanNode(itemName);
        String portType = provider.getPortType(itemName);
        int portNumber = provider.getPortNumber(itemName);
        logger.trace("Type: {}, portNumber: {}, command: {}", portType, portNumber, command.toString());
        byte[] messageBytes;
        if (portType.equals("d") && portNumber == 1 && command instanceof OnOffType) {
            boolean state = OnOffType.ON.equals(command) ? true : false;
            DigitalMessage message = new DigitalMessage((byte) canNode, state);
            messageBytes = message.getRaw();
        } else if (portType.equals("a") && (portNumber - 1) % 4 == 0 && command instanceof DecimalType) {
            TACmiMeasureType measureType = provider.getMeasureType(itemName);
            AnalogMessage message = new AnalogMessage((byte) canNode, 1, (DecimalType) command, measureType);
            messageBytes = message.getRaw();
        } else {
            logger.info("Not sending command: portType: {}, portNumber: {}, command: {}", portType, portNumber,
                    command.toString());
            return;
        }
        DatagramPacket packet = new DatagramPacket(messageBytes, messageBytes.length, cmiAddress,
                TACmiBinding.cmiPort);
        try {
            clientSocket.send(packet);
        } catch (IOException e) {
            logger.warn("Error sending message: {}, {}", e.getClass().getName(), e.getMessage());
        }
    }
}

From source file:org.cc86.MMC.client.Main.java

public static String serverDiscovery() {
    String res = "0.0.0.0";
    DatagramSocket c;/*from  www . j  a v  a2s  .  c o m*/
    // Find the server using UDP broadcast
    try {
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 0xCC86);
            c.send(sendPacket);
            l.info("Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        // Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue; // Don't want to broadcast to the loopback interface
            }

            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress broadcast = interfaceAddress.getBroadcast();
                if (broadcast == null) {
                    continue;
                }

                // Send the broadcast package!
                try {
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                    c.send(sendPacket);
                } catch (Exception e) {
                }

                l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: "
                        + networkInterface.getDisplayName());
            }
        }

        l.info("Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_MMC_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            res = (receivePacket.getAddress() + "").substring(1);
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {

    }
    return res;
}

From source file:org.opennms.netmgt.syslogd.SyslogdEventdLoadTest.java

@Test
@Transactional//from  w  w w.ja  v  a 2  s .co  m
public void testRfcSyslog() throws Exception {
    loadSyslogConfiguration("/etc/syslogd-rfc-configuration.xml");

    startSyslogdGracefully();

    m_eventCounter.anticipate();

    InetAddress address = InetAddress.getLocalHost();

    // handle an invalid packet
    byte[] bytes = "<34>1 2010-08-19T22:14:15.000Z localhost - - - - BOMfoo0: load test 0 on tty1\0".getBytes();
    DatagramPacket pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    WaterfallExecutor.waterfall(m_executorServices, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP,
            MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI));

    // handle a valid packet
    bytes = "<34>1 2003-10-11T22:14:15.000Z plonk -ev/pts/8\0".getBytes();
    pkt = new DatagramPacket(bytes, bytes.length, address, SyslogClient.PORT);
    WaterfallExecutor.waterfall(m_executorServices, new SyslogConnection(pkt, MATCH_PATTERN, HOST_GROUP,
            MESSAGE_GROUP, UEI_LIST, HIDE_MESSAGE, DISCARD_UEI));

    m_eventCounter.waitForFinish(120000);

    assertEquals(1, m_eventCounter.getCount());
}

From source file:org.graylog2.inputs.transports.UdpTransportTest.java

private void sendUdpDatagram(String hostname, int port, int size) throws IOException {
    final InetAddress address = InetAddress.getByName(hostname);
    final byte[] data = new byte[size];
    final DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

    DatagramSocket toSocket = null;
    try {//from w ww. j av a  2 s . c o m
        toSocket = new DatagramSocket();
        toSocket.send(packet);
    } finally {
        if (toSocket != null) {
            toSocket.close();
        }
    }
}

From source file:com.webobjects.monitor.application.HostsPage.java

private boolean hostMeetsMinimumVersion(InetAddress anAddress) {
    byte[] versionRequest;

    try {/*from w  w w  .  ja  va 2s .com*/
        versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException uee) {
        versionRequest = ("womp://queryVersion").getBytes();
    }
    DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress,
            WOApplication.application().lifebeatDestinationPort());

    byte[] mbuffer = new byte[1000];
    DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length);
    DatagramSocket socket = null;

    try {
        socket = new DatagramSocket();
        socket.send(outgoingPacket);
        incomingPacket.setLength(mbuffer.length);
        socket.setSoTimeout(2000);
        socket.receive(incomingPacket);
        String reply = new String(incomingPacket.getData());
        if (reply.startsWith("womp://replyVersion/")) {
            int lastIndex = reply.lastIndexOf(":webObjects");
            lastIndex += 11;
            String version = reply.substring(lastIndex);
            if (version.equals("4.5")) {
                return false;
            }
        } else {
            return false;
        }
    } catch (InterruptedIOException iioe) {
        return true;
    } catch (SocketException se) {
        return true;
    } catch (Throwable e) {
        return false;
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    return true;
}

From source file:org.psit.transwatcher.TransWatcher.java

private String connectAndGetCardIP() {
    DatagramSocket clientSocket = null, serverSocket = null;

    try {//from   w  ww.j av a  2 s. co  m
        String broadcastIP = getBroadcastIP();
        setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD);
        notifyMessage("BroadcastIP: " + broadcastIP);

        // send out broadcast
        clientSocket = new DatagramSocket(58255);
        InetAddress IPAddress = InetAddress.getByName(broadcastIP);
        byte[] sendData = "".getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777);
        clientSocket.send(sendPacket);
        clientSocket.close();

        serverSocket = new DatagramSocket(58255);
        byte[] receiveData = new byte[256];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.setSoTimeout(3000);
        serverSocket.receive(receivePacket);
        serverSocket.close();

        notifyMessage("Packet received: " + new String(receiveData));
        if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0)
            return receivePacket.getAddress().getHostAddress();
    } catch (Exception ex) {
        notifyMessage("Card handshake unsuccessful. ");
        notifyException(ex);
    } finally {
        if (clientSocket != null)
            clientSocket.close();
        if (serverSocket != null)
            serverSocket.close();
    }
    return null;
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Send the provided message to the socket.
 *
 * @param socket the socket//w  w w.java  2s.  c om
 * @param nt the nt
 * @param message the message
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static void sendMessage(DatagramSocket socket, String nt, String message) throws IOException {
    String msg = buildMsg(nt, message);
    //Random rand = new Random();

    // logger.trace( "Sending this SSDP packet: " + CRLF + StringUtils.replace(msg, CRLF, "<CRLF>")));

    InetAddress upnpAddress = getUPNPAddress();
    DatagramPacket ssdpPacket = new DatagramPacket(msg.getBytes(), msg.length(), upnpAddress, UPNP_PORT);
    socket.send(ssdpPacket);

    // XXX Why is it necessary to sleep for this random time? What would happen when random equals 0?
    //sleep(rand.nextInt(1800 / 2));

    // XXX Why send the same packet twice?
    //socket.send(ssdpPacket);

    // XXX Why is it necessary to sleep for this random time (again)?
    //sleep(rand.nextInt(1800 / 2));
}

From source file:QuoteServerThread.java

void doIt(int port) {
        DatagramPacket packet;//from  w ww  .j  ava  2  s  .c om
        byte[] sendBuf = new byte[256];

        packet = new DatagramPacket(sendBuf, 256, address, port);

        try { // send request
            if (DEBUG) {
                System.out.println("Applet about to send packet to address " + address + " at port " + port);
            }
            socket.send(packet);
            if (DEBUG) {
                System.out.println("Applet sent packet.");
            }
        } catch (IOException e) {
            System.out.println("Applet socket.send failed:");
            e.printStackTrace();
            return;
        }

        packet = new DatagramPacket(sendBuf, 256);

        try { // get response
            if (DEBUG) {
                System.out.println("Applet about to call socket.receive().");
            }
            socket.receive(packet);
            if (DEBUG) {
                System.out.println("Applet returned from socket.receive().");
            }
        } catch (IOException e) {
            System.out.println("Applet socket.receive failed:");
            e.printStackTrace();
            return;
        }

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

From source file:energy.usef.core.util.DateTimeUtil.java

private static synchronized String getUDPInfo(String message) {
    try {//from   ww  w. j ava2 s . c o  m
        LOGGER.debug("SENDING: {}", message);
        byte[] buf = message.getBytes();
        InetAddress address = InetAddress.getByName(serverIp);
        DatagramSocket socket = new DatagramSocket();
        socket.send(new DatagramPacket(buf, buf.length, address, port));
        DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER);
        socket.disconnect();
        socket.setSoTimeout(RESPONSE_TIMEOUT);
        socket.receive(result);
        socket.disconnect();
        socket.close();
        String resultStr = new String(result.getData()).trim();
        LOGGER.debug("RECEIVED: {} ", resultStr);
        errorCount = 0;
        return resultStr;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        errorCount++;
        if (errorCount >= MAX_ERROR_COUNT) {
            LOGGER.error("Unable to run simulation correctly.");
            System.exit(1);
        }
    }
    return null;
}