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) 

Source Link

Document

Constructs a DatagramPacket for receiving packets of length length .

Usage

From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.discovery.UDPDiscoveryReceiver.java

/**
 * Highly unreliable. If it is processing one message while another comes in ,
 * the second message is lost. This is for low concurency peppering.
 *
 * @return the object message// ww w  . j  a  v  a  2  s. c o m
 * @throws IOException
 */
public Object waitForMessage() throws IOException {
    final DatagramPacket packet = new DatagramPacket(m_buffer, m_buffer.length);

    Object obj = null;
    try {
        m_socket.receive(packet);

        final ByteArrayInputStream byteStream = new ByteArrayInputStream(m_buffer, 0, packet.getLength());

        final ObjectInputStream objectStream = new ObjectInputStream(byteStream);

        obj = objectStream.readObject();

    } catch (Exception e) {
        log.error("Error receving multicast packet", e);
    }
    return obj;
}

From source file:MulticastClient.java

public void run() {

        while (moreQuotes) {
            try {
                byte[] buf = new byte[256];

                // receive request
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);//from  www  .j a v a  2s . c o  m

                // figure out response
                String dString = null;
                if (in == null)
                    dString = new Date().toString();
                else
                    dString = getNextQuote();
                buf = dString.getBytes();

                // send the response to the client at "address" and "port"
                InetAddress address = packet.getAddress();
                int port = packet.getPort();
                packet = new DatagramPacket(buf, buf.length, address, port);
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
                moreQuotes = false;
            }
        }
        socket.close();
    }

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

/**
 * @{inheritDoc//  w ww .  j  ava  2s .  co  m
 */
@Override
protected void execute() {
    logger.trace("execute() method is called!");
    try {
        clientSocket.setBroadcast(true);
        clientSocket.setSoTimeout(10000);
        byte[] receiveData = new byte[14];
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        byte[] data = receivePacket.getData();
        Message message;
        if (data[1] > 0) {
            logger.debug("Processing analog message");
            message = new AnalogMessage(data);
        } else if (data[1] == 0) {
            logger.debug("Processing digital message");
            message = new DigitalMessage(data);
        } else {
            logger.debug("Invalid message received");
            return;
        }
        logger.debug(message.toString());
        for (TACmiBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                logger.debug("Processing item: " + itemName);
                int portNumber = provider.getPortNumber(itemName);
                if (provider.getCanNode(itemName) == message.canNode
                        && provider.getPortType(itemName).equals(message.getType().toString().toLowerCase())) {
                    if (message.hasPortnumber(portNumber)) {
                        if (message.getType() == MessageType.A) {
                            AnalogValue value = ((AnalogMessage) message).getAnalogValue(portNumber);
                            if (value.value != null) {
                                logger.debug("Updating item: " + itemName + " with value: " + value.value);
                                eventPublisher.postUpdate(itemName, new DecimalType(value.value));
                            }
                        } else {
                            OnOffType state = ((DigitalMessage) message).getPortStateAsOnOffType(portNumber);
                            logger.debug("Updating item {} with state {}", itemName, state);
                            eventPublisher.postUpdate(itemName, state);
                        }
                    } else {
                        logger.debug("Portnumber {} not included in message", portNumber);
                    }
                } else {
                    logger.debug("CAN Node does not match");
                }
            }
        }

    } catch (Exception e) {
        logger.warn("Error in execute: {}, Message: {}", e.getClass().getName(), e.getMessage());
    }
    logger.trace("TACmi execute() finished");

}

From source file:org.necsave.NecsaveTransport.java

public void broadcast(Message msg) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ProtoOutputStream pos = new ProtoOutputStream(baos);
    msg.setMedium(MEDIUM.IP_BROADCAST);/* w  w w . ja va 2  s. c  om*/
    int length = msg.serialize(pos);
    DatagramPacket packet = new DatagramPacket(baos.toByteArray(), length);
    for (int i = 0; i < 3; i++)
        packet.setSocketAddress(new InetSocketAddress("255.255.255.255", broadcastPort + i));
    serverSocket.send(packet);
}

From source file:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void datagramPacket_length_zero() {
    UDPReceiver receiver = null;//from w  w  w  .  j  av a2  s .  com
    DatagramSocket datagramSocket = null;

    CountDownLatch latch = new CountDownLatch(1);
    Executor mockExecutor = mockDispatchWorker(latch);

    PacketHandlerFactory packetHandlerFactory = mock(PacketHandlerFactory.class);
    when(packetHandlerFactory.createPacketHandler()).thenReturn(loggingPacketHandler);

    try {
        InetSocketAddress bindAddress = new InetSocketAddress(ADDRESS, PORT);
        ObjectPoolFactory<DatagramPacket> packetFactory = new DatagramPacketFactory();
        ObjectPool<DatagramPacket> pool = new DefaultObjectPool<>(packetFactory, 10);
        receiver = new UDPReceiver("test", packetHandlerFactory, mockExecutor, 8, bindAddress, pool) {
            @Override
            boolean validatePacket(DatagramPacket packet) {
                interceptValidatePacket(packet);
                return super.validatePacket(packet);
            }
        };
        receiver.start();

        datagramSocket = new DatagramSocket();
        datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

        datagramSocket.send(new DatagramPacket(new byte[0], 0));
        datagramSocket.send(new DatagramPacket(new byte[1], 1));

        Assert.assertTrue(latch.await(30000, TimeUnit.MILLISECONDS));
        Assert.assertEquals(zeroPacketCounter.get(), 1);
        Mockito.verify(mockExecutor).execute(any(Runnable.class));
    } catch (Exception e) {
        logger.debug(e.getMessage(), e);
        Assert.fail(e.getMessage());
    } finally {
        if (receiver != null) {
            receiver.shutdown();
        }
        IOUtils.closeQuietly(datagramSocket);

    }
}

From source file:com.iiitd.networking.UDPMessenger.java

public void startMessageReceiver() {
    Runnable receiver = new Runnable() {

        @Override/* w  ww .j a  v  a 2s . c om*/
        public void run() {
            WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wim != null) {
                MulticastLock mcLock = wim.createMulticastLock(TAG);
                mcLock.acquire();
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket rSocket;

            try {
                rSocket = new MulticastSocket(MULTICAST_PORT);
            } catch (IOException e) {
                Log.d(DEBUG_TAG, "Impossible to create a new MulticastSocket on port " + MULTICAST_PORT);
                e.printStackTrace();
                return;
            }

            while (receiveMessages) {
                try {
                    rSocket.receive(rPacket);
                } catch (IOException e1) {
                    Log.d(DEBUG_TAG, "There was a problem receiving the incoming message.");
                    e1.printStackTrace();
                    continue;
                }

                if (!receiveMessages)
                    break;

                byte data[] = rPacket.getData();
                int i;
                for (i = 0; i < data.length; i++) {
                    if (data[i] == '\0')
                        break;
                }

                String messageText;

                try {
                    messageText = new String(data, 0, i, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.d(DEBUG_TAG, "UTF-8 encoding is not supported. Can't receive the incoming message.");
                    e.printStackTrace();
                    continue;
                }

                try {
                    incomingMessage = new Message(messageText, rPacket.getAddress());
                } catch (IllegalArgumentException ex) {
                    Log.d(DEBUG_TAG, "There was a problem processing the message: " + messageText);
                    ex.printStackTrace();
                    continue;
                }

                incomingMessageHandler.post(getIncomingMessageAnalyseRunnable());
            }
        }

    };

    receiveMessages = true;
    if (receiverThread == null)
        receiverThread = new Thread(receiver);

    if (!receiverThread.isAlive())
        receiverThread.start();
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

private void sendResponse(final SocketAddress addr) {
    if (!(addr instanceof InetSocketAddress)) {
        LOG.warn("Don't know how to handle non Internet addresses");
        return;//from  w ww  .ja  va 2s  . c o m
    }
    DatagramSocket sock = null;
    LOG.debug("Responding to " + addr.toString());

    try {
        sock = new DatagramSocket();
        sock.connect(addr);
        byte[] ba = generateSearchResponse().getBytes();
        sock.send(new DatagramPacket(ba, ba.length));
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } finally {
        if (sock != null) {
            sock.close();
        }
    }
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
@Ignore/* w  ww  . j  av  a  2 s . c  om*/
public void verifySendMulticast() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    final String multicastAddress = "225.6.7.8";
    final String payload = "foo";
    final CountDownLatch latch1 = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    Runnable catcher = new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[8];
                DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
                MulticastSocket socket = new MulticastSocket(testPort);
                InetAddress group = InetAddress.getByName(multicastAddress);
                socket.joinGroup(group);
                latch1.countDown();
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
                socket.receive(receivedPacket);
                socket.close();
                byte[] src = receivedPacket.getData();
                int length = receivedPacket.getLength();
                int offset = receivedPacket.getOffset();
                byte[] dest = new byte[length];
                System.arraycopy(src, offset, dest, 0, length);
                assertEquals(payload, new String(dest));
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
                latch2.countDown();
            } catch (Exception e) {
                noMulticast = true;
                latch1.countDown();
                e.printStackTrace();
            }
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    latch1.await(3000, TimeUnit.MILLISECONDS);
    if (noMulticast) {
        return;
    }
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(3000, TimeUnit.MILLISECONDS));
    handler.shutDown();
}

From source file:ws.argo.Responder.Responder.java

public void run() throws IOException, ClassNotFoundException {

    ArrayList<ProbeHandlerPluginIntf> handlers = new ArrayList<ProbeHandlerPluginIntf>();

    // load up the handler classes specified in the configuration parameters
    // I hope the hander classes are in a jar file on the classpath
    handlers = loadHandlerPlugins(cliValues.config.appHandlerConfigs);

    @SuppressWarnings("resource")
    MulticastSocket socket = new MulticastSocket(cliValues.config.multicastPort);
    address = InetAddress.getByName(cliValues.config.multicastAddress);
    LOGGER.info("Starting Responder on " + address.toString() + ":" + cliValues.config.multicastPort);
    socket.joinGroup(address);// www.java 2 s. c o  m

    DatagramPacket packet;
    ResponsePayloadBean response = null;

    LOGGER.info(
            "Responder started on " + cliValues.config.multicastAddress + ":" + cliValues.config.multicastPort);

    httpClient = HttpClients.createDefault();

    LOGGER.fine("Starting Responder loop - infinite until process terminated");
    // infinite loop until the responder is terminated
    while (true) {

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        LOGGER.fine("Waiting to recieve packet...");
        socket.receive(packet);

        LOGGER.fine("Received packet");
        LOGGER.fine("Packet contents:");
        // Get the string
        String probeStr = new String(packet.getData(), 0, packet.getLength());
        LOGGER.fine("Probe: \n" + probeStr);

        try {
            ProbePayloadBean payload = parseProbePayload(probeStr);

            LOGGER.info("Received probe id: " + payload.probeID);

            // Only handle probes that we haven't handled before
            // The Probe Generator needs to send a stream of identical UDP packets
            // to compensate for UDP reliability issues.  Therefore, the Responder
            // will likely get more than 1 identical probe.  We should ignore duplicates.
            if (!handledProbes.contains(payload.probeID)) {
                for (ProbeHandlerPluginIntf handler : handlers) {
                    response = handler.probeEvent(payload);
                    sendResponse(payload.respondToURL, payload.respondToPayloadType, response);
                }
                handledProbes.add(payload.probeID);
            } else {
                LOGGER.info("Discarding duplicate probe with id: " + payload.probeID);
            }

        } catch (SAXException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

    }

}

From source file:ws.argo.mcg.GatewaySender.java

/**
 * Run the main sender process.// w ww  . j  a  v a2  s .  c  o m
 * 
 */
public void run() {

    if (!this.joinGroup())
        return; // If we can't join the group, end the process

    DatagramPacket packet;

    LOGGER.fine("Starting Gateway loop - infinite until process terminated");
    // infinite loop until the responder is terminated
    while (true) {

        byte[] buf = new byte[2048];
        packet = new DatagramPacket(buf, buf.length);
        LOGGER.fine("Waiting to recieve packet on " + maddress + ":" + multicastPort);
        try {
            inboundSocket.receive(packet);
            new GSHandlerThread(packet, unicastAddress, unicastPort, allowLoopback).start();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Error handling inbound TCP packet", e);
        }

    }

}