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, SocketAddress address) 

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.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {//w  w  w.ja v a  2s.com

        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT);

        // Request-Packet-Constructor
        StringBuffer discoveryMessage = new StringBuffer();
        discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n");
        discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n");
        discoveryMessage.append("ST: upnp:rootdevice\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\r\n");
        discoveryMessage.append("\r\n");
        logger.trace("Request: {}", discoveryMessage.toString());
        byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes();
        DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length,
                dstAddress);

        // Send multi-cast packet
        MulticastSocket multicast = null;
        try {
            multicast = new MulticastSocket(null);
            multicast.bind(srcAddress);
            logger.trace("Source-Address = '{}'", srcAddress);
            multicast.setTimeToLive(4);
            logger.debug("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        DatagramSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    receivePacket = new DatagramPacket(new byte[1536], 1536);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    logger.trace("Received message: {}", message);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String label = "WeMo Device";
                            String wemoUDN = null;
                            String wemoLocation = null;
                            String wemoFriendlyName = null;
                            String wemoModelName = null;
                            ThingUID uid = null;

                            if (message != null) {
                                if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
                                        || message.contains("Motion-1_0")
                                        || message.contains("Lightswitch-1_0")) {
                                    wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
                                            "::upnp:rootdevice");
                                    logger.debug("Wemo device with UDN '{}' found", wemoUDN);
                                    wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
                                            "/setup.xml");
                                    if (wemoLocation != null) {
                                        try {
                                            int timeout = 5000;
                                            String response = HttpUtil.executeUrl("GET",
                                                    wemoLocation + "/setup.xml", timeout);
                                            wemoFriendlyName = StringUtils.substringBetween(response,
                                                    "<friendlyName>", "</friendlyName>");
                                            logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
                                                    wemoLocation);
                                            wemoModelName = StringUtils.substringBetween(response,
                                                    "<modelName>", "</modelName>");
                                            logger.trace("Wemo device '{}' has model name '{}'",
                                                    wemoFriendlyName, wemoModelName);
                                            label = "Wemo" + wemoModelName;

                                            switch (wemoModelName) {
                                            case "Socket":
                                                logger.debug(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);

                                                break;
                                            case "Insight":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
                                                break;
                                            case "LightSwitch":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
                                                break;
                                            case "Motion":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
                                                break;
                                            }
                                            Map<String, Object> properties = new HashMap<>(4);
                                            properties.put(UDN, wemoUDN);
                                            properties.put(LOCATION, wemoLocation);

                                            DiscoveryResult result = DiscoveryResultBuilder.create(uid)
                                                    .withProperties(properties).withLabel(label).build();
                                            thingDiscovered(result);

                                        } catch (Exception te) {
                                            logger.error("Could not discover WeMo device", te);
                                        }
                                    }
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not send Wemo device discovery", e);
    }

}

From source file:org.apache.hadoop.metrics.ganglia.GangliaContext.java

protected void emitMetric(String name, String type, String value) throws IOException {
    String units = getUnits(name);
    int slope = getSlope(name);
    int tmax = getTmax(name);
    int dmax = getDmax(name);

    offset = 0;//from   w  ww  . java 2 s  . c o m
    xdr_int(0); // metric_user_defined
    xdr_string(type);
    xdr_string(name);
    xdr_string(value);
    xdr_string(units);
    xdr_int(slope);
    xdr_int(tmax);
    xdr_int(dmax);

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }
}

From source file:org.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testAsMapFalse() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);/* w w w.j a  v  a 2  s  .co  m*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    DefaultMessageConverter defaultMessageConverter = new DefaultMessageConverter();
    defaultMessageConverter.setAsMap(false);
    adapter.setConverter(defaultMessageConverter);
    Thread.sleep(1000);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE".getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    Message<?> message = outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("WEBERN", message.getHeaders().get("syslog_HOST"));
    assertEquals("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE",
            new String((byte[]) message.getPayload(), "UTF-8"));
    adapter.stop();
}

From source file:org.avineas.fins.gw.Gateway.java

/**
 * The after properties set method of this gateway. The method initializes
 * a new thread that continuously reads from the UDP port for getting data
 * for local (or remote) nodes. This method <b>must</b> be called before
 * actual receiving of data can take place.
 *///from  w  w  w . j a  va  2  s .  co  m
@PostConstruct
public void init() throws SocketException {
    if (thread != null)
        return;
    if (channel == null)
        setPort(9600);

    // Initialize the nodes and handling of the packets.
    thread = new Thread() {
        @SuppressWarnings("synthetic-access")
        @Override
        public void run() {
            byte[] data = new byte[Frame.MAXFRAMESIZE];
            logger.info(Gateway.this + " started");
            for (;;) {
                try {
                    // Read a datagram from the network
                    DatagramPacket dpacket = new DatagramPacket(data, 0, data.length);
                    channel.receive(dpacket);

                    // Update the FINS node/gateway information
                    Destination dest = new Destination(dpacket.getAddress(), dpacket.getPort());
                    traceDatagram(dest + " -> " + channel.getLocalPort(), dpacket);
                    Frame packet = new Frame(data, dpacket.getLength());
                    Address from = packet.getSource();
                    setDestination(from.getNodeAsString(), dest);

                    // Handle the packet. It is either forwarded to
                    // a remote machine or locally handled. 
                    // Note that there is a possibility that gateways keep
                    // each other busy with sending data to each other. This
                    // cannot be prevented here.
                    Address to = packet.getDestination();
                    NodeUnit unit = units.get(to.toString());
                    if (unit != null) {
                        logger.info("received " + (packet.isReply() ? "reply" : "packet") + " frame from: "
                                + dest + ", for local unit: " + to + " from: " + packet.getSource());
                        Frame reply = unit.handleFrame(packet);
                        if (reply != null)
                            send(reply);
                    } else {
                        logger.info("frame for node " + to + " cannot be handled locally, trying forward");
                        send(packet);
                    }
                } catch (Exception exc) {
                    if (!runDown) {
                        synchronized (this) {
                            // Will normally only occur when the port is changed on the fly
                            logger.error("exception handling frame", exc);
                        }
                    }
                }
                // In case we were shut down, stop
                if (runDown)
                    break;
            }
            logger.info("FINS gateway shutdown complete");
        }
    };
    thread.start();
}

From source file:org.loggo.server.SimpleServerIT.java

@Test(timeout = 60 * 1000)
public void sunnyDay() throws Exception {
    // no log files exist
    assertEquals(0, Iterators.size(conn.createScanner("logs", Authorizations.EMPTY).iterator()));
    // send a tcp message
    Socket s = new Socket("localhost", loggerPort);
    assertTrue(s.isConnected());/*w ww .ja  v a 2 s  .com*/
    s.getOutputStream()
            .write("localhost tester 2014-01-01 01:01:01,123 This is a test message\n\n".getBytes(UTF_8));
    s.close();
    // send a udp message
    DatagramSocket ds = new DatagramSocket();
    String otherMessage = "localhost test2 2014-01-01 01:01:01,345 [INFO] This is a 2nd message";
    byte[] otherMessageBytes = otherMessage.getBytes(UTF_8);
    InetSocketAddress dest = new InetSocketAddress("localhost", loggerPort);
    ds.send(new DatagramPacket(otherMessageBytes, otherMessageBytes.length, dest));
    ds.close();
    // wait for a flush
    sleepUninterruptibly(8, TimeUnit.SECONDS);
    // verify the messages are stored
    Scanner scanner = conn.createScanner("logs", Authorizations.EMPTY);
    assertEquals(2, Iterators.size(scanner.iterator()));
    Iterator<Entry<Key, Value>> iter = scanner.iterator();
    Entry<Key, Value> next = iter.next();
    assertEquals(next.getValue().toString(), "This is a test message");
    assertEquals(next.getKey().getColumnQualifier().toString(), "tester\0localhost");
    assertEquals(next.getKey().getColumnFamily().toString(), "UNKNOWN");
    assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123"));
    next = iter.next();
    assertEquals(next.getValue().toString(), "[INFO] This is a 2nd message");
    assertEquals(next.getKey().getColumnQualifier().toString(), "test2\0localhost");
    assertTrue(next.getKey().getRow().toString().endsWith("2014-01-01 01:01:01,123"));
    assertFalse(iter.hasNext());
    sleepUninterruptibly(30, TimeUnit.SECONDS);
    conn.tableOperations().deleteRows("logs", null, null);
}

From source file:com.cloudera.flume.reporter.ganglia.GangliaSink.java

/**
 * This takes a metric and then send it off to the listening ganglia gmond
 * ports via udp.//ww  w .  jav a 2  s .  co m
 * 
 * This is not thread safe.
 */
private void emitMetric(String name, String type, String value, String units) throws IOException {
    int slope = 3; // see gmetric.c
    int tmax = DEFAULT_TMAX;
    int dmax = DEFAULT_DMAX;
    String hostName = NetUtils.localhost();

    // First we send out a metadata message
    xdr_int(128); // metric_id = metadata_msg
    xdr_string(hostName); // hostname
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string(type); // metric type
    xdr_string(name); // metric name
    xdr_string(units); // units
    xdr_int(slope); // slope
    xdr_int(tmax); // tmax, the maximum time between metrics
    xdr_int(dmax); // dmax, the maximum data value
    xdr_int(1); // ???

    /*
     * Num of the entries in extra_value field for Ganglia 3.1.x
     */
    xdr_string("GROUP"); /* Group attribute */
    xdr_string(DEFAULT_GROUP); /* Group value */

    // send to each ganglia metrics listener/server
    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }

    // Now we send out a message with the actual value.
    // Technically, we only need to send out the metadata message once for
    // each metric, but I don't want to have to record which metrics we did and
    // did not send.
    offset = 0;
    xdr_int(133); // we are sending a string value
    xdr_string(hostName); // hostName
    xdr_string(name); // metric name
    xdr_int(0); // spoof = False
    xdr_string("%s"); // format field
    xdr_string(value); // metric value

    for (SocketAddress socketAddress : metricsServers) {
        DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
        datagramSocket.send(packet);
    }

}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
 * Send a SSDP search message with the given search target (ST) and return a list of received responses.
 *//*  www.  j a  v a 2 s .  c  om*/
public Map<String, URL> discover(String searchTarget) {
    Log.d("HUE", "ServiceDiscovery.discover");
    final InetSocketAddress address;
    // standard multicast port for SSDP
    try {
        // multicast address with administrative scope
        address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
        //address = InetAddress.getByName(MULTICAST_ADDRESS);

    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not get multicast address", e);
    }

    final MulticastSocket socket;
    try {
        socket = new MulticastSocket(null);

        InetAddress localhost = getAndroidLocalIP();

        InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT);
        Log.d("HUE", "" + srcAddress.getAddress());
        socket.bind(srcAddress);
        Log.d("HUE", "step 1");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not create multicast socket");
    }

    try {
        socket.setSoTimeout(socketTimeout);
        Log.d("HUE", "step 2");
    } catch (SocketException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set socket timeout", e);
    }

    try {
        socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
        Log.d("HUE", "step 3");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e);
    }
    try {
        socket.setTimeToLive(ttl);
        Log.d("HUE", "step 4");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set TTL " + ttl, e);
    }
    final byte[] transmitBuffer;
    try {
        transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME);
        Log.d("HUE", "step 5");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e);
    }
    DatagramPacket packet = null;
    try {
        packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address);
        Log.d("HUE", "step 6");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.send(packet);
        Log.d("HUE", "step 7");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not send search request", e);
    }
    Map<String, URL> result = new HashMap<String, URL>();
    byte[] receiveBuffer = new byte[1536];
    while (true) {
        try {
            Log.d("HUE", "sending packets");
            final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length,
                    InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
            socket.receive(receivePacket);
            //Log.d("HUE", new String(receivePacket.getData()));
            HueBridge response = parseResponsePacket(receivePacket);
            if (response != null) {
                Log.d("HUE", "resonse not null");
                ////System.out.println("resonse not null");
                result.put(response.getUDN(), response.getBaseUrl());
            } else {
                Log.d("HUE", "no bridge");
            }
        } catch (SocketTimeoutException e) {
            Log.e("HUE", "timeout exception");
            break;
        } catch (IOException e) {
            throw new IllegalStateException("Problem receiving search responses", e);
        }
    }
    return result;
}

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

@Override
public void run() {
    if (parent.getRemote() == null) {
        throw new IllegalArgumentException("No user data set for remote user");
    }/*  w ww.  j  a v a  2  s  . com*/

    logger.info("Started listening to port: " + port);
    while (running && channel.isBound()) {

        byte[] bt = new byte[bufferSize];

        try {
            if (mode == ConnectionMode.BINDING) {
                logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - "
                        + channel.getPort());
                Thread.sleep(5); //No reason to hammer on this

                DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
                channel.receive(packet);
                SocketAddress currentSender = packet.getSocketAddress();

                sender = currentSender;
                byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());
                logger.info("Received data: " + Hex.encodeHexString(data) + " on "
                        + channel.getLocalSocketAddress() + " - " + channel.getPort());

                byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                        parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

                ByteBuffer outData = ByteBuffer.wrap(out);
                logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender);

                DatagramPacket pc = new DatagramPacket(out, 0, out.length);
                pc.setSocketAddress(sender);
                channel.send(pc);

                this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode
                logger.info("-> DTLS handshake");
            } else if (mode == ConnectionMode.HANDSHAKE) {
                Thread.sleep(5);
                logger.info("In handshake mode: ");

                if (transport == null) {
                    channel.connect(sender);

                    /**
                     * {@link NioUdpTransport} might replace the {@link UDPTransport} here.
                     * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a>
                     */
                    transport = serverProtocol.accept(dtlsServer,
                            new DtlsMuxStunTransport(parent, channel, MTU));
                }

                sctpService = new SCTPImpl(this);

                mode = ConnectionMode.TRANSFER;
                logger.info("-> SCTP mode");
            } else if (mode == ConnectionMode.TRANSFER) {

                /**
                 * Here we receive message and put them to a worker thread for handling
                 * If the output of handling the message is a message, then we send those
                 * using the same thread.
                 */
                byte[] buf = new byte[transport.getReceiveLimit()];
                int length = transport.receive(buf, 0, buf.length, waitMillis);
                if (length >= 0) {
                    byte[] handled = Arrays.copyOf(buf, length);
                    workPool.submit(() -> {
                        try {
                            List<byte[]> data = sctpService.handleRequest(handled);
                            data.forEach(this::putDataOnWire);
                        } catch (Exception e) {
                            logger.error("Failed handling message: ", e);
                        }
                    });
                    logger.debug("Input: " + Hex.encodeHexString(handled));
                }
            }
        } catch (Exception e) {
            logger.error("Com error:", e);
            logger.info("Shutting down, we cannot continue here");
            running = false; //Need to quit channel now
        }
    }
    workPool.shutdown();
}

From source file:org.apache.hadoop.metrics2.sink.ganglia.AbstractGangliaSink.java

/**
 * Sends Ganglia Metrics to the configured hosts
 * @throws IOException//from w ww .  java 2  s. com
 */
protected void emitToGangliaHosts() throws IOException {
    try {
        for (SocketAddress socketAddress : metricsServers) {
            DatagramPacket packet = new DatagramPacket(buffer, offset, socketAddress);
            datagramSocket.send(packet);
        }
    } finally {
        // reset the buffer for the next metric to be built
        offset = 0;
    }
}

From source file:com.carreygroup.JARVIS.Demon.java

public boolean Send(Packet p) throws IOException {
    boolean ret = false;
    if ((Ethnet_Mode == Ethnet.TCP) || (Ethnet_Mode == Ethnet.P2P)) {
        ByteBuffer bytebufOut = ByteBuffer.allocate(Ethnet.BUFFER_SIZE);
        bytebufOut = ByteBuffer.wrap(p.toByteArray());
        try {//from w ww  . j  av  a  2 s .c o m
            mPrintWriterClient.print(new String(bytebufOut.array()));//
            mPrintWriterClient.flush();
            ret = true;
        } catch (Exception e) {
            notifyDisconnected();
            throw new IOException("");
        }
        bytebufOut.flip();
        bytebufOut.clear();
    }

    if (Ethnet_Mode == Ethnet.UDP) {
        byte[] buff = p.toByteArray();
        DatagramPacket packet = new DatagramPacket(buff, buff.length, mAddress);
        mSendPSocket.send(packet);//
        ret = true;
    }
    return ret;
}