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: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());//  www.ja  v  a2s  . c om
    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.ionicsdk.discovery.Discovery.java

public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) {
    new AsyncTask<Integer, Void, Void>() {

        @Override/*from  w w  w . j  a v  a  2 s  .  co m*/
        protected Void doInBackground(Integer... params) {
            try {
                DatagramSocket socket = new DatagramSocket();
                socket.setBroadcast(true);

                String data = opts.toString();

                DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
                        getBroadcastAddress(), opts.getInt("port"));
                socket.send(packet);
                Log.d(TAG, "Sent packet");

                byte[] buf = new byte[1024];
                packet = new DatagramPacket(buf, buf.length);
                socket.receive(packet);

                String result = new String(buf, 0, packet.getLength());

                Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result);

                callbackContext.success(result);

            } catch (Exception e) {
                callbackContext.error(e.getMessage());
                Log.e(TAG, "Exception while listening for server broadcast");
                e.printStackTrace();
            }
            return null;
        }
    }.execute();

}

From source file:us.nineworlds.serenity.core.services.GDMService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {//from w ww  .j a  va  2  s  .com
        DatagramSocket socket = new DatagramSocket(32414);
        socket.setBroadcast(true);
        String data = "M-SEARCH * HTTP/1.1\r\n\r\n";
        DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(),
                32414);
        //         DatagramPacket packet = new DatagramPacket(data.getBytes(),
        //               data.length(), getBroadcastAddress(), 32414);

        socket.send(packet);
        Log.d("GDMService", "Search Packet Broadcasted");

        byte[] buf = new byte[256];
        packet = new DatagramPacket(buf, buf.length);
        socket.setSoTimeout(2000);
        boolean listening = true;
        while (listening) {
            try {
                socket.receive(packet);
                String packetData = new String(packet.getData());
                if (packetData.contains("HTTP/1.0 200 OK")) {
                    Log.d("GDMService", "PMS Packet Received");
                    // Broadcast Received Packet
                    Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED);
                    packetBroadcast.putExtra("data", packetData);
                    packetBroadcast.putExtra("ipaddress", packet.getAddress().toString());
                    LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast);
                }
            } catch (SocketTimeoutException e) {
                Log.d("GDMService", "Socket Timeout");
                socket.close();
                listening = false;
                Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED);
                LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast);
            }

        }
    } catch (IOException e) {
        Log.e("GDMService", e.toString());
    }

}

From source file:poisondog.net.udp.SendMission.java

public Void execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket();

    socket.setReuseAddress(true);/* w ww.j av a 2  s  .c o  m*/
    socket.setBroadcast(parameter.getBroadcast());

    if (parameter.getTimeout() > 0)
        socket.setSoTimeout(parameter.getTimeout());

    String data = IOUtils.toString(parameter.getInputStream());
    DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length());
    packet.setAddress(InetAddress.getByName(parameter.getHost()));
    if (parameter.getPort() > 0)
        packet.setPort(parameter.getPort());
    socket.send(packet);
    socket.close();
    return null;
}

From source file:org.openhim.mediator.engine.connectors.UDPFireForgetConnector.java

private void sendRequest(final MediatorSocketRequest req) {
    try {//w w  w. j av a2  s . c  om
        final DatagramSocket socket = new DatagramSocket();

        ExecutionContext ec = getContext().dispatcher();
        Future<Boolean> f = future(new Callable<Boolean>() {
            public Boolean call() throws IOException {
                InetAddress addr = InetAddress.getByName(req.getHost());
                byte[] payload = req.getBody().getBytes();
                DatagramPacket packet = new DatagramPacket(payload, payload.length, addr, req.getPort());

                socket.send(packet);

                return Boolean.TRUE;
            }
        }, ec);
        f.onComplete(new OnComplete<Boolean>() {
            @Override
            public void onComplete(Throwable throwable, Boolean result) throws Throwable {
                try {
                    if (throwable != null) {
                        throw throwable;
                    }
                } catch (Exception ex) {
                    log.error(ex, "Exception");
                } finally {
                    IOUtils.closeQuietly(socket);
                }
            }
        }, ec);
    } catch (Exception ex) {
        log.error(ex, "Exception");
    }
}

From source file:com.example.nate.cloudcar.MainActivity.java

public void socketSend(final String chan, final int pos) {
    new Thread(new Runnable() {
        public void run() {
            try {
                int msgLength = chan.length();
                DatagramSocket s = new DatagramSocket();
                InetAddress local = InetAddress.getByName("192.168.10.200");
                byte[] message = chan.getBytes();
                DatagramPacket chanPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(chanPacket);
                msgLength = Integer.toString(pos).length();
                message = Integer.toString(pos).getBytes();
                DatagramPacket posPacket = new DatagramPacket(message, msgLength, local, server_port);
                s.send(posPacket);//from ww  w .j ava  2  s  .c o  m
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    Thread.currentThread().interrupted();

}

From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java

@Test
public void testUdpEchoServer() throws IOException {
    SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder()
            .withConfig(//from  www  . jav a 2s.  c om
                    SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build())
            .withConnectorFactory(UdpConnectorFactory.Builder.builder()
                    .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build())
            .build();
    simpleNbServer.start();
    String message1 = "this is message1";
    String message2 = "this is message2";
    String message3 = "quit";
    try {
        DatagramSocket socket = new DatagramSocket();
        SocketAddress address = new InetSocketAddress("localhost", 1111);

        // message 1
        byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address);
        socket.send(packet);
        byte[] response = new byte[50];
        DatagramPacket responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message1, messageRead);

        // message2
        byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address);
        socket.send(packet2);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals(message2, messageRead);

        // message3
        byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address);
        socket.send(packet3);
        responsePacket = new DatagramPacket(response, response.length);
        socket.receive(responsePacket);
        messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength());
        Assert.assertEquals("goodbye", messageRead);

    } finally {
        simpleNbServer.shutdown();
    }
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();//from  w w w .j a v a 2  s .  co m
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java

/**
 * Returns the network address with which the task manager shall announce itself to the job manager. To determine
 * the address this method exchanges packets with the job manager.
 * /* ww  w.  ja  v a  2s  .  c  o  m*/
 * @param jobManagerAddress
 *        the address of the job manager
 * @return the address with which the task manager shall announce itself to the job manager
 * @throws DiscoveryException
 *         thrown if an error occurs during the packet exchange
 */
public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException {

    final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER);
    final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT);

    InetAddress taskManagerAddress = null;
    DatagramSocket socket = null;

    try {

        socket = new DatagramSocket();
        LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT);
        socket.setSoTimeout(CLIENTSOCKETTIMEOUT);

        final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE],
                RESPONSE_PACKET_SIZE);

        for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) {

            final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber);
            addressRequest.setAddress(jobManagerAddress);
            addressRequest.setPort(discoveryPort);

            LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress());
            socket.send(addressRequest);

            try {
                socket.receive(responsePacket);
            } catch (SocketTimeoutException ste) {
                LOG.warn("Timeout wainting for task manager address reply. Retrying...");
                continue;
            }

            if (!isPacketForUs(responsePacket, magicNumber)) {
                LOG.warn("Received packet which is not destined to this Nephele setup");
                continue;
            }

            final int packetTypeID = getPacketTypeID(responsePacket);
            if (packetTypeID != TM_ADDRESS_REPLY_ID) {
                LOG.warn("Received response of unknown type " + packetTypeID + ", discarding...");
                continue;
            }

            taskManagerAddress = extractInetAddress(responsePacket);
            break;
        }

    } catch (IOException ioe) {
        throw new DiscoveryException(StringUtils.stringifyException(ioe));
    } finally {
        if (socket != null) {
            socket.close();
        }
    }

    if (taskManagerAddress == null) {
        throw new DiscoveryException("Unable to obtain task manager address");
    }

    return taskManagerAddress;
}

From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {// w  w w  .j  a va2s  .c om

        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);
    }

}