Example usage for java.net DatagramSocket send

List of usage examples for java.net DatagramSocket send

Introduction

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

Prototype

public void send(DatagramPacket p) throws IOException 

Source Link

Document

Sends a datagram packet from this socket.

Usage

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Send a single packet of the size indicated and wait for a response.
 * //from w w  w.jav a2s  . c  o  m
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);

    return endTime - startTime;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * //from  w  w  w .  j a va2s  .c om
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    return retval;
}

From source file:com.kecso.socket.ServerSocketControl.java

@Override
public void run() {
    DatagramSocket sock = null;

    try {// w  w  w.ja  v a2s  .  c om
        sock = new DatagramSocket(8888);
        sock.setSoTimeout(1000);

        byte[] buffer = new byte[65536];
        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

        while (!Thread.currentThread().isInterrupted()) {
            try {
                sock.receive(incoming);
                byte[] data = incoming.getData();
                this.udpMessage = SerializationUtils.deserialize(data);

                byte[] response = SerializationUtils.serialize(
                        this.output != null
                                ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(),
                                        (float) output.getAltitude(), (float) output.getRpm())
                                : null);
                DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(),
                        incoming.getPort());
                sock.send(dp);
            } catch (SocketTimeoutException e) {
            }
        }
    } catch (Exception e) {
        System.err.println("IOException " + e);
    } finally {
        if (sock != null) {
            sock.close();
        }

    }
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoapHAI.java

private int dtnObservationRequest(Node node, Resource resource) throws VitroGatewayException, IOException {
    int requestMsgId = UNDEFINED_COAP_MESSAGE_ID; // TODO: ??? we will use the packetID as a message ID to return.
    String proxyAddress = getProxyAddress(node);
    if (proxyAddress != null) {
        String moteUriResource = "";
        if (MoteResource.containsValue(resource)) {
            //moteUriResource += MoteResource.getMoteUriResource(resource);
            String theResourceName = MoteResource.getMoteUriResource(resource);
            if (theResourceName == null) {
                logger.error("unsupported resource");
                return UNDEFINED_COAP_MESSAGE_ID;
            }//from   w  ww . j  a  v a  2 s. c o m
            // FOR TCS adapter, we prefer the TEMPERATURE_TCS
            // FOR WLAB and HAI we prefer the TEMPERATURE_ALT
            // we do this check because the getMoteUriResource is making a reverse lookup in the hashmap (where two keys point to the same resource)
            if (theResourceName.compareToIgnoreCase(MoteResource.TEMPERATURE_TCS) == 0) {
                theResourceName = MoteResource.TEMPERATURE_ALT;
            }
            moteUriResource += theResourceName;
            int packetID = UNDEFINED_COAP_MESSAGE_ID;
            do { //while loop to avoid a packetID that exists in the array that is to be ignored!
                packetID = random.nextInt(65535) + 1;
            } while (timedOut_DTN_CoapMessageIDsList.contains(Integer.valueOf(packetID))
                    || packetID == UNDEFINED_COAP_MESSAGE_ID);

            String msgString = packetID + "#" + node.getId() + "#" + RESOURCE_REQ + "#" + moteUriResource;
            byte[] msgBytes = new byte[Constants.DTN_MESSAGE_SIZE];
            msgBytes = msgString.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(msgBytes, msgBytes.length,
                    InetAddress.getByName(proxyAddress), Constants.PROXY_UDPFORWARDER_PORT);
            DatagramSocket clientSocket = new DatagramSocket();
            clientSocket.send(sendPacket);
            clientSocket.close();
            requestMsgId = packetID;
            logger.info("Sent Request: " + msgString);
        } else {
            logger.warn("No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
            throw new WSIAdapterException(
                    "No resource mapping for Node " + node.getId() + " and Resource " + resource.getName());
        }
    } else {
        logger.warn("No available proxy for Node " + node.getId() + " is found");
        throw new WSIAdapterException("No available proxy for Node " + node.getId() + " is found");
    }
    return requestMsgId;
}

From source file:com.mobiperf.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * /*from  w w w .java 2s .co  m*/
 * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the
 * total time is the time for the first packet to leave until the last packet arrives. AFter 7000
 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets
 * lost is recorded.
 * 
 * @param serverAddr server to which to send the packets
 * @param size size of the packets
 * @param num number of packets to send
 * @param packetSize size of the packets sent
 * @param port port to send the packets to
 * @return first value: the amount of time to send all packets and get a response. second value:
 *         number of packets lost, on a timeout.
 * @throws IOException
 */
public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port)
        throws IOException {

    long startTime = 0;
    long endTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[packetSize];
    long[] retval = { -1, -1 };
    long numLost = 0;
    int i = 0;
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    // number * (packet sent + packet received)
    dataConsumedThisTask += num * (size + packetSize);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");
        for (i = 0; i < num; i++) {
            socket.send(packet);
        }
        for (i = 0; i < num; i++) {
            socket.receive(packetRcv);
            if (i == 0) {

                endTime = System.currentTimeMillis();
            }
        }
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out");
        numLost += (num - i);
        socket.close();
    }
    Logger.d("Sending complete: " + endTime);

    retval[0] = endTime - startTime;
    retval[1] = numLost;

    incrementData(dataConsumedThisTask);
    return retval;
}

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

@Test
public void datagramPacket_length_zero() {
    UDPReceiver receiver = null;//  w  ww . ja v a  2s .c  o m
    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:org.apache.nifi.processors.standard.TestListenUDP.java

protected void run(final DatagramSocket socket, final List<String> messages, final int expectedQueueSize,
        final int expectedTransferred) throws IOException, InterruptedException {

    try {//from  w w w  .j  a v a 2 s.  c om
        // schedule to start listening on a random port
        final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory();
        final ProcessContext context = runner.getProcessContext();
        proc.onScheduled(context);
        Thread.sleep(100);

        // get the real port the dispatcher is listening on
        final int destPort = proc.getDispatcherPort();
        final InetSocketAddress destination = new InetSocketAddress("localhost", destPort);

        // send the messages to the port the processors is listening on
        for (final String message : messages) {
            final byte[] buffer = message.getBytes(StandardCharsets.UTF_8);
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length, destination);
            socket.send(packet);
            Thread.sleep(10);
        }

        long responseTimeout = 10000;

        // this first loop waits until the internal queue of the processor has the expected
        // number of messages ready before proceeding, we want to guarantee they are all there
        // before onTrigger gets a chance to run
        long startTimeQueueSizeCheck = System.currentTimeMillis();
        while (proc.getQueueSize() < expectedQueueSize
                && (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) {
            Thread.sleep(100);
        }

        // want to fail here if the queue size isn't what we expect
        Assert.assertEquals(expectedQueueSize, proc.getQueueSize());

        // call onTrigger until we processed all the messages, or a certain amount of time passes
        int numTransferred = 0;
        long startTime = System.currentTimeMillis();
        while (numTransferred < expectedTransferred
                && (System.currentTimeMillis() - startTime < responseTimeout)) {
            proc.onTrigger(context, processSessionFactory);
            numTransferred = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS).size();
            Thread.sleep(100);
        }

        // should have transferred the expected events
        runner.assertTransferCount(ListenUDP.REL_SUCCESS, expectedTransferred);
    } finally {
        // unschedule to close connections
        proc.onUnscheduled();
        IOUtils.closeQuietly(socket);
    }
}

From source file:org.jini.commands.multicast.MulticastSender.java

private void startMulticastSender() throws NoSuchAlgorithmException {
    byte[] outBuf;
    // Interval in MiliSeconds
    final int INTERVAL = this.getInterval();
    // Port /*from www .ja v a 2s.c o  m*/
    final int PORT = this.getPort();
    // Multicast Group
    String mcastGroup = this.getMulticastGroup();

    String fl = this.getFile();
    String fileName = this.getFile();

    // Read Data from File
    String msg = this.getFileContents(fileName);
    // MD5 CheckSum
    String mdfiveSum = this.checkFileMD5(fileName);

    // Jini Logging
    JiniCommandsLogger jcl = new JiniCommandsLogger();

    System.out.println("Started Multicast Sender. Sending Datagram every : " + INTERVAL + " Miliseconds");
    if (logDatagramMessages == true) {
        System.out.println("Logging to Directory : " + jcl.getJiniLogDir());
    } else {
        System.out.println("Logging not turned on, add -l to start logging. ");

    }
    System.out.println("'c + ENTER' or 'x + ENTER' to stop Multicast Sender.");

    PrintChar printChar = new PrintChar();
    printChar.setOutPutChar(">");

    try {
        Scanner in = new Scanner(System.in);

        printChar.start();

        DatagramSocket socket = new DatagramSocket();
        long counter = 0;

        while (this.running) {
            // Every 10th broadcast the file is checked if it has changed (MD5). 
            // If it has the new data is read and broadcasted
            counter++;
            if (counter == 10) {
                if (mdfiveSum.equals(this.checkFileMD5(fileName)) == false) {
                    msg = this.getFileContents(fileName);
                }
                counter = 0;
            }

            outBuf = msg.getBytes();

            //Send to multicast IP address and port
            InetAddress address = InetAddress.getByName(mcastGroup);
            DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);

            socket.send(outPacket);

            if (logDatagramMessages == true) {
                jcl.writeLog(msg);
            }

            if ((in.nextLine().equalsIgnoreCase("c")) || (in.nextLine().equalsIgnoreCase("x"))) {
                this.running = false;
            }

            try {
                Thread.sleep(INTERVAL);
            } catch (InterruptedException ie) {
                printChar.setStopPrinting(true);
                this.setJcError(true);
                this.addErrorMessages("Error : An error occured in the Sleep thread.");
            }
        }
    } catch (IOException ioe) {
        printChar.setStopPrinting(true);
        /*
         DatagramPacket is just a wrapper on a UDP based socket, so the usual UDP rules apply.
         64 kilobytes is the theoretical maximum size of a complete IP datagram, but only 576 bytes are guaranteed to be routed. 
         On any given network path, the link with the smallest Maximum Transmit Unit will determine the actual limit. (1500 bytes,
         less headers is the common maximum, but it is impossible to predict how many headers there will be so its safest to limit 
         messages to around 1400 bytes.)
         If you go over the MTU limit, IPv4 will automatically break the datagram up into fragments and reassemble them at the end, 
         but only up to 64 kilobytes and only if all fragments make it through. If any fragment is lost, or if any device decides 
         it doesn't like fragments, then the entire packet is lost.
                 
         As noted above, it is impossible to know in advance what the MTU of path will be. There are various algorithms for experimenting 
         to find out, but many devices do not properly implement (or deliberately ignore) the necessary standards so it all comes down to 
         trial and error. Or you can just guess 1400 bytes per message.
         As for errors, if you try to send more bytes than the OS is configured to allow, you should get an EMSGSIZE error or its equivalent.
         If you send less than that but more than the network allows, the packet will just disappear.
         */

        this.setJcError(true);
        this.addErrorMessages("Info : 64 kilobytes is the theoretical maximum size of a complete IP Datagram");
        this.addErrorMessages("Error : " + ioe);
    }

    printChar.setStopPrinting(true);
    this.done = true;
}

From source file:org.openacs.HostsBean.java

public void RequestConnectionUDP(String url, String user, String pass) throws Exception {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);//from www.ja  v  a 2s.  c o  m
    s.bind(new InetSocketAddress(Application.getSTUNport()));
    String ts = Long.toString(Calendar.getInstance().getTimeInMillis());
    String id = ts;
    Random rnd = new Random();
    byte[] nonceArray = new byte[16];
    rnd.nextBytes(nonceArray);

    String cn = cvtHex.cvtHex(nonceArray);
    url = url.substring(6);
    String[] u = url.split(":");

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    String data = ts + id + user + cn;
    byte[] rawHmac = mac.doFinal(data.getBytes());
    String signature = cvtHex.cvtHex(rawHmac);
    String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig="
            + signature + " HTTP/1.1\r\n\r\n";

    byte[] breq = req.getBytes();
    DatagramPacket packet = new DatagramPacket(breq, breq.length);
    packet.setAddress(InetAddress.getByName(u[0]));
    packet.setPort(Integer.parseInt(u[1]));
    s.send(packet);
}

From source file:net.fenyo.gnetwatch.actions.ActionFlood.java

/**
 * Floods the target./*from  w w  w  .  j av  a 2  s. c om*/
 * @param none.
 * @return void.
 * @throws IOException IO exception.
 * @throws InterruptedException exception.
 */
public void invoke() throws IOException, InterruptedException {
    if (isDisposed() == true)
        return;

    try {
        super.invoke();

        // il faudrait copier les queriers  la cration de l'action
        final IPQuerier querier;

        DatagramSocket socket;
        final byte[] buf;
        final DatagramPacket packet;
        // on invoque un champ persistent depuis potentiellement un thread autre que celui qu gre une session qui rend cet objet persistent, on doit viter cet accs concurrent (les sessions ne sont pas thread safe)
        synchronized (getGUI().getSynchro()) {
            if (TargetIPv4.class.isInstance(getTarget())) {
                querier = ((TargetIPv4) getTarget()).getIPQuerier();
            } else if (TargetIPv6.class.isInstance(getTarget())) {
                querier = ((TargetIPv6) getTarget()).getIPQuerier();
            } else
                return;

            socket = new DatagramSocket(querier.getPortSrc());
            socket.setTrafficClass(querier.getTos() << 2);
            socket.setBroadcast(true);

            buf = new byte[querier.getPDUMaxSize()];
            Arrays.fill(buf, (byte) 0);
            packet = new DatagramPacket(buf, buf.length,
                    new InetSocketAddress(querier.getAddress(), querier.getPortDst()));
        }

        long last_time = System.currentTimeMillis();
        int bytes_sent = 0;
        while (true) {
            socket.send(packet);
            bytes_sent += buf.length;

            if (System.currentTimeMillis() - last_time > 1000) {

                synchronized (getGUI().getSynchro()) {
                    synchronized (getGUI().sync_tree) {
                        final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(this);

                            getTarget().addEvent(new EventFlood(new Double(
                                    ((double) 8 * 1000 * bytes_sent) / (System.currentTimeMillis() - last_time))
                                            .intValue()));

                            setDescription(
                                    GenericTools.formatNumericString(getGUI().getConfig(),
                                            "" + new Double(((double) 8 * 1000 * bytes_sent)
                                                    / (System.currentTimeMillis() - last_time)).intValue())
                                            + " bit/s");

                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }

                synchronized (getGUI().getSynchro()) {
                    getGUI().setStatus(getGUI().getConfig().getPattern("bytes_flooded", bytes_sent,
                            querier.getAddress().toString().substring(1)));
                }

                last_time = System.currentTimeMillis();
                bytes_sent = 0;
            }

            if (interrupted == true) {
                socket.close();
                return;
            }
        }
    } catch (final InterruptedException ex) {
    }
}