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:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.cluster.impl.RelayClusterReceiverImpl.java

@Override
public void run() {
    byte[] receiveBuffer = new byte[UplinkReceiver.BUFFERSIZE];
    DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);

    while (this.run.get()) {
        try {/*from   w  w  w. j a va 2 s  .com*/
            this.sock.receive(packet);

            InetAddress ip = packet.getAddress();
            int port = packet.getPort();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("received packet from RelayServer " + ip.getHostAddress() + ":" + port);
            }

            RelayServer me = this.relayServers.getMe();
            if (!(ip.equals(me.getIp()) && (port != this.relayClusterUdpPort))) {
                DatagramPacket msg = RelayClusterMessage.fromWireFormat(packet, this.reportOnce);
                if (msg != null) {
                    RelayServer rs = this.relayServers.getOrAdd(ip, port);
                    boolean packetCausedUpdate = this.packetHandler.processPacket(rs, msg);
                    if (this.relayClusterForwarding && packetCausedUpdate) {
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug(
                                    "forwarding packet from RelayServer " + ip.getHostAddress() + ":" + port);
                        }
                        this.relayClusterSender.addPacket(rs, msg);
                    }
                } else {
                    this.logger.error("Could not convert RelayClusterMessage from wire format");
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("skipping packet from RelayServer " + ip.getHostAddress() + ":" + port
                            + " since the packet came from me");
                }
            }
        } catch (Exception e) {
            if (!SocketException.class.equals(e.getClass())) {
                e.printStackTrace();
            }
        }
    }

    if (this.sock != null) {
        this.sock.close();
        this.sock = null;
    }
}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * /*from ww  w  .  j ava2s. c  om*/
 *  
 */
public void testTurnOnWhenOff() {

    /* Data to send */
    byte[] dataToSend = message.getBytes();

    /* Error code -- gets modified if exceptions occur. */
    boolean error = false;

    /* Attempt to connect to the specified IP/Port using UDP */
    this.udpComm.turnOn();

    /* Allow server socket to fully start */
    synchronized (this) {
        try {
            this.wait(1000);
        } catch (InterruptedException e2) {
            /* Do nothing */
        }
        this.notifyAll();
    }

    /* Make a client */
    DatagramSocket clientSocket = null;
    try {
        clientSocket = new DatagramSocket(this.udpComm.getRemotePort());
    } catch (SocketException e) {
        logger.debug(this.getName() + ": " + e.getMessage());
        error = true;
    }

    /* Send out a packet of data */
    try {
        this.udpComm.getSendBuffer().addToBuffer(dataToSend);
    } catch (DataBufferInterruptedException dbie) {
        logger.debug(this.getName() + ": " + dbie.getMessage());
        error = true;
    }

    /* Receive the packet of data */
    if (clientSocket != null) {
        /* Set a timeout for receiving data */
        try {
            clientSocket.setSoTimeout(1000);
        } catch (SocketException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Make a new packet to hold the received data */
        DatagramPacket dataPacket = new DatagramPacket(new byte[1024], 1024);

        /* Attempt to receive the data */
        try {
            clientSocket.receive(dataPacket);
        } catch (IOException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Check that the data was received succesfully */
        if (!error) {
            logger.debug("Client received: " + new String(dataPacket.getData()));
        } else {
            logger.debug(this.getName() + ": client did not receive message.");
            error = true;
        }

        clientSocket.disconnect();

        clientSocket.close();
        clientSocket = null;

    }

    /* Check to see if any errors happened. */
    assertFalse(error);

}

From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java

@Test()
@Ignore("Can only be executed if an Asterix sender is feeding the decoder")
public void when_upd_unicast_is_used_as_input_should_decode_cat062_messages_from_larger_sample()
        throws IOException {
    //arrange/*from   w w  w.j  a  v  a 2  s. c  om*/
    final int PORT = 3002;
    final int MAX_PACKET_SIZE = 65507;
    final int TIMEOUT = 5000;

    //act
    AsterixDecoder decoder = new AsterixDecoder(62, 65);
    byte[] networkBuffer = new byte[MAX_PACKET_SIZE];
    int receivedDatagrams = 0;
    int receivedBytes = 0;
    try (DatagramSocket client = new DatagramSocket(PORT)) {
        client.setSoTimeout(TIMEOUT);
        DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length);
        while (true) {
            client.receive(packet);
            decoder.decode(networkBuffer, 0, packet.getLength());

            //accumulate and print info
            receivedDatagrams++;
            receivedBytes += packet.getLength();
            if (receivedDatagrams % 100 == 0) {
                System.out
                        .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes");
            }
        }
    } catch (IOException e) {
        System.out.println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes");
    }

    //assert
    int expectedDatagrams = 18163;
    int expectedBytes = 2785805;
    assertEquals(expectedDatagrams, receivedDatagrams);
    assertEquals(expectedBytes, receivedBytes);
}

From source file:org.necsave.NecsaveTransport.java

private Message readMessage() throws Exception {
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    serverSocket.receive(receivePacket);

    ProtoInputStream pis = new ProtoInputStream(new ByteArrayInputStream(receiveData),
            ProtoDefinition.getInstance());

    Message msg = ProtoDefinition.getInstance().nextMessage(pis);

    if (msg instanceof PlatformInfo)
        process((PlatformInfo) msg, receivePacket.getAddress().getHostAddress(), receivePacket.getPort());

    NeptusLog.pub().debug("Received message of type '" + msg.getAbbrev() + "' from "
            + receivePacket.getAddress() + " - Platform " + platformNames.get(msg.getSrc()));

    return msg;/*w w  w  .j a va  2 s .c  o  m*/
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.distributor.impl.DistributorWorkerImpl.java

private DatagramPacket toPacket(List<PositionUpdateMsg> positionUpdateMsgs, int positionUpdateMsgsByteCount) {
    assert (positionUpdateMsgs != null);
    assert (positionUpdateMsgs.size() > 0);
    assert (positionUpdateMsgsByteCount > 0);
    assert (positionUpdateMsgsByteCount <= this.packetMaxSize);

    DatagramPacket packet = new DatagramPacket(new byte[positionUpdateMsgsByteCount],
            positionUpdateMsgsByteCount);
    byte[] packetData = packet.getData();
    int packetDataIndex = 0;
    for (PositionUpdateMsg positionUpdateMsg : positionUpdateMsgs) {
        byte[] positionUpdateMsgData = positionUpdateMsg.getPositionUpdateMsg().getData();
        int positionUpdateMsgDataLength = positionUpdateMsgData.length;
        System.arraycopy(positionUpdateMsgData, 0, packetData, packetDataIndex, positionUpdateMsgDataLength);
        packetDataIndex += positionUpdateMsgDataLength;
    }//from   w ww .  j  a  v  a  2 s .c o  m

    return packet;
}

From source file:ru.novoscan.trkpd.snmp.spring.TrackSpringSnmpAgent.java

public void run() {
    try {/*from   w ww  .  j  ava  2s .c  om*/
        logger.debug("Binding to UDP port " + listeningPort);
        socket = new DatagramSocket(listeningPort);
    } catch (SocketException e) {
        // Fix: Flag to control lock socket within application
        isSocketException = true;
        throw new SnmpSystemException("Can not create SNMP agent UDP socket. Reason: " + e.getMessage());
    }

    // Fix: Flag to control lock socket within application
    isSocketCreated = true;

    while (!workerThread.isInterrupted()) {
        byte requestPacketBuffer[] = new byte[PACKET_MAX_SIZE];
        final DatagramPacket requestPacket = new DatagramPacket(requestPacketBuffer,
                requestPacketBuffer.length);
        try {
            socket.receive(requestPacket);
        } catch (IOException e) {
            logger.error("Error processing SNMP request. Reason: " + e.getMessage());
            continue;
        }
        final byte data[] = requestPacket.getData();
        Thread procThread = new Thread(new Runnable() {

            public void run() {
                try {
                    Message requestMsg;
                    Message responseMsg;
                    PDU requestPDU;
                    // Fix: Added missed ')' character
                    logger.debug("Received packet (length=" + data.length + " bytes)");
                    BerTlv tlv = new BerTlv();
                    tlv.decode(new ByteArrayInputStream(data));
                    requestMsg = new Message(tlv);
                    responseMsg = null;
                    requestPDU = (PDU) requestMsg.getPDU();
                    String requestedOID = requestPDU.getVarBindList().getVarBind(0).getObjectName()
                            .stringValue();

                    if (!hasHandledPrefix(requestedOID)) {

                        logger.info("No entry found for oid " + requestedOID);
                        GetResponsePDU responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 2, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                        return;
                    }

                    if (!validateCommunity(requestMsg)) {
                        logger.warn(
                                "Community [" + requestMsg.getComunity() + "] doesn't match for snmp request");
                        return;
                    }

                    GetResponsePDU responsePDU = null;
                    if (requestPDU instanceof GetRequestPDU)
                        responsePDU = handleGetRequest((GetRequestPDU) requestPDU);
                    else if (requestPDU instanceof GetNextRequestPDU)
                        responsePDU = handleGetNextRequest((GetNextRequestPDU) requestPDU);
                    else if (requestPDU instanceof SetRequestPDU)
                        responsePDU = handleSetRequest((SetRequestPDU) requestPDU);
                    else
                        responsePDU = createErrorResponse(requestPDU.getRequestId(), 5, 0,
                                requestPDU.getVarBindList());
                    responseMsg = new Message(0, requestMsg.getComunity(), responsePDU);

                    logger.info("Sending response to client\n" + responseMsg.toString());
                    byte responsePacketBuffer[] = responseMsg.toBerTlv().getBytes();
                    if (responsePacketBuffer.length > PACKET_MAX_SIZE) {
                        responsePDU = new GetResponsePDU(requestPDU.getRequestId(), 1, 0L,
                                requestPDU.getVarBindList());
                        responseMsg = new Message(SNMP_VERSION, requestMsg.getComunity(), responsePDU);
                        responsePacketBuffer = responseMsg.toBerTlv().getBytes();
                    }
                    DatagramPacket responsePacket = new DatagramPacket(responsePacketBuffer,
                            responsePacketBuffer.length, requestPacket.getAddress(), requestPacket.getPort());
                    socket.send(responsePacket);
                } catch (Exception e) {
                    logger.error("Error processing SNMP request. Reason: " + e.getMessage());
                }
            }
        });
        procThread.start();
    }
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTP.java

/***
 * This method synchronizes a connection by discarding all packets that
 * may be in the local socket buffer.  This method need only be called
 * when you implement your own TFTP client or server.
 * <p>/*from w  ww. j  a  v  a 2  s . c o  m*/
 * @exception IOException if an I/O error occurs.
 ***/
public final void discardPackets() throws IOException {
    int to;
    DatagramPacket datagram;

    datagram = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE);

    to = getSoTimeout();
    setSoTimeout(1);

    try {
        while (true)
            _socket_.receive(datagram);
    } catch (SocketException e) {
        // Do nothing.  We timed out so we hope we're caught up.
    } catch (InterruptedIOException e) {
        // Do nothing.  We timed out so we hope we're caught up.
    }

    setSoTimeout(to);
}

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;//from   w  w  w.j  av a2 s  . c  om
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:org.apache.webdav.lib.NotificationListener.java

/**
 * /*from   w  ww  . j av a 2s .c  om*/
 * @param host The ip-address on which the udp or http-server is running (e.g. "localhost")
 * @param port The port where the udp or http-server is listening on (e.g. 4444)
 * @param repositoryHost The ip-adress of the WebDAV-repository
 * @param repositoryPort The port of the WebDAV-repository (e.g. 8080)
 * @param protocol The protocol that should be used to connect to the WebDAV-repository (http or https) 
 * @param credentials The credentials which are used to connect to the WebDAV-repository 
 * @param repositoryDomain The repository domain (e.g. "/slide")
 * @param pollInterval The poll interval that will be used if no notifications are revieved via UDP/TCP
 * @param udp If set to true, UDP server will be started, otherwise TCP server (must match the repository notification mode)
 */
public NotificationListener(String host, int port, String repositoryHost, int repositoryPort, Protocol protocol,
        Credentials credentials, String repositoryDomain, int pollInterval, boolean udp) {
    this.credentials = credentials;
    this.notificationHost = host;
    this.notificationPort = port;
    this.repositoryHost = repositoryHost;
    this.repositoryPort = repositoryPort;
    this.protocol = protocol;
    this.repositoryDomain = repositoryDomain;
    this.udp = udp;

    if (udp) {
        Thread listenerThread = new Thread(new Runnable() {
            public void run() {
                DatagramSocket serverSocket = null;
                try {
                    serverSocket = new DatagramSocket(notificationPort);
                    while (true) {
                        byte[] buf = new byte[256];
                        DatagramPacket packet = new DatagramPacket(buf, buf.length);
                        serverSocket.receive(packet);
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new ByteArrayInputStream(buf)));
                        parseNotification(reader);
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Error while listening to socket", e);
                }
            }
        });
        listenerThread.setDaemon(true);
        listenerThread.start();
    } else {
        Thread listenerThread = new Thread(new Runnable() {
            public void run() {
                ServerSocket serverSocket = null;
                try {
                    serverSocket = new ServerSocket(notificationPort);
                    while (true) {
                        new ConnectionThread(serverSocket.accept()).start();
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Error while listening to socket", e);
                }
            }
        });
        listenerThread.setDaemon(true);
        listenerThread.start();
    }

    TimerTask poll = new TimerTask() {
        public void run() {
            if (subscribersAsString != null) {
                poll(subscribersAsString);
            }
        }
    };
    timer.schedule(poll, pollInterval, pollInterval);
}

From source file:org.lwes.listener.DatagramEnqueuer.java

/**
 * While running, repeatedly read datagrams and insert them into the queue along with the
 * receipt time and other metadata./* w ww .  j ava2 s.  c  om*/
 */
@Override
public void run() {
    running = true;

    while (running) {
        try {
            DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
            socket.receive(datagram);
            if (log.isTraceEnabled()) {
                log.trace("Received datagram: " + datagram);
            }
            /* we record the time *after* the receive because it blocks */
            long receiptTime = System.currentTimeMillis();

            /* copy the data into a tight buffer so we can release the loose buffer */
            final byte[] tightBuffer = new byte[datagram.getLength()];
            System.arraycopy(datagram.getData(), 0, tightBuffer, 0, tightBuffer.length);
            datagram.setData(tightBuffer);

            /* create an element for the queue */
            DatagramQueueElement element = new DatagramQueueElement();
            element.setPacket(datagram);
            element.setTimestamp(receiptTime);

            /* add the element to the queue and notify everyone there's work to do */
            queue.put(element);
            if (log.isTraceEnabled()) {
                log.trace("Enqueued: " + element);
            }
        } catch (Exception e) {
            log.warn("Unable to read datagram", e);
        }
    }
}