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.streamsets.pipeline.stage.origin.udp.TestUDPSource.java

private void doBasicTest(UDPDataFormat dataFormat) throws Exception {
    List<String> ports = NetworkUtils.getRandomPorts(2);
    ParserConfig parserConfig = new ParserConfig();
    parserConfig.put(CHARSET, "UTF-8");
    TUDPSource source = new TUDPSource(ports, parserConfig, dataFormat, 20, 100L);
    SourceRunner runner = new SourceRunner.Builder(TUDPSource.class, source).addOutputLane("lane").build();
    runner.runInit();/*from   w ww . j  av a  2s  . c  o  m*/
    try {
        byte[] bytes = null;
        switch (dataFormat) {
        case NETFLOW:
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(TEN_PACKETS_RESOURCE);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            is.close();
            baos.close();
            bytes = baos.toByteArray();
            break;
        case SYSLOG:
            bytes = "<34>1 2003-10-11T22:14:15.003Z mymachine.example.com some syslog data"
                    .getBytes(StandardCharsets.UTF_8);
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        for (String port : ports) {
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress address = InetAddress.getLoopbackAddress();
            DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address,
                    Integer.parseInt(port));
            clientSocket.send(sendPacket);
            clientSocket.close();
        }
        StageRunner.Output output = runner.runProduce(null, 6);
        Assert.assertTrue(source.produceCalled);
        List<Record> records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 6, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), ports.size(), records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 14);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 14, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), 0, records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 1);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        Assert.assertEquals(String.valueOf(records), 0, records.size());
    } finally {
        runner.runDestroy();
    }
}

From source file:com.example.android.toyvpn.ToyVpnService.java

private void UDPtoProxy(ByteBuffer packet) throws IOException {
    //TODO FARE un THREAD??
    final DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("localhost");
    //send Pkt to Proxy
    DatagramPacket sendPacket = new DatagramPacket(packet.array(), packet.array().length, IPAddress,
            mServerPort);/*w ww. j av a2 s.  co  m*/
    clientSocket.send(sendPacket);
}

From source file:org.kde.kdeconnect.Backends.LanBackend.LanLinkProvider.java

@Override
public void onStart() {

    //This handles the case when I'm the existing device in the network and receive a "hello" UDP package

    udpAcceptor.setHandler(udpHandler);// w  w w .  j  av a2  s. c o  m

    try {
        udpAcceptor.bind(new InetSocketAddress(port));
    } catch (Exception e) {
        Log.e("LanLinkProvider", "Error: Could not bind udp socket");
        e.printStackTrace();
    }

    boolean success = false;
    int tcpPort = port;
    while (!success) {
        try {
            tcpAcceptor.bind(new InetSocketAddress(tcpPort));
            success = true;
        } catch (Exception e) {
            tcpPort++;
        }
    }

    Log.i("LanLinkProvider", "Using tcpPort " + tcpPort);

    //I'm on a new network, let's be polite and introduce myself
    final int finalTcpPort = tcpPort;
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            String deviceListPrefs = PreferenceManager.getDefaultSharedPreferences(context)
                    .getString(KEY_CUSTOM_DEVLIST_PREFERENCE, "");
            ArrayList<String> iplist = new ArrayList<String>();
            if (!deviceListPrefs.isEmpty()) {
                iplist = CustomDevicesActivity.deserializeIpList(deviceListPrefs);
            }
            iplist.add("255.255.255.255");
            for (String ipstr : iplist) {
                try {
                    InetAddress client = InetAddress.getByName(ipstr);
                    NetworkPackage identity = NetworkPackage.createIdentityPackage(context);
                    identity.set("tcpPort", finalTcpPort);
                    byte[] b = identity.serialize().getBytes("UTF-8");
                    DatagramPacket packet = new DatagramPacket(b, b.length, client, port);
                    DatagramSocket socket = new DatagramSocket();
                    socket.setReuseAddress(true);
                    socket.setBroadcast(true);
                    socket.send(packet);
                    //Log.i("LanLinkProvider","Udp identity package sent to address "+packet.getAddress());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("LanLinkProvider",
                            "Sending udp identity package failed. Invalid address? (" + ipstr + ")");
                }
            }

            return null;

        }

    }.execute();

}

From source file:org.motechproject.metrics.impl.StatsdAgentBackendImpl.java

private boolean doSend(DatagramSocket sock, String stat) {
    if (serverAddr == null) {
        try {//w  ww  .ja  v a2s  .c  o  m
            serverAddr = InetAddress.getByName(serverHost);
        } catch (UnknownHostException e) {
            //log.error(e.getMessage());
            return false;
        }
    }

    try {
        byte[] data = stat.getBytes();
        sock.send(new DatagramPacket(data, data.length, serverAddr, serverPort));
        return true;
    } catch (IOException e) {
        //log.error(String.format("Could not send stat %s to host %s:%d", stat, serverHost, serverPort), e);
    }
    return false;
}

From source file:org.rifidi.emulator.reader.alien.heartbeat.HeartbeatController.java

/**
 * Send out a heartbeat//w  ww  .j  av  a  2  s  . c  o m
 */
private void broadcast() {
    String retString = "<Alien-RFID-Reader-Heartbeat>\n" + "  <ReaderName>Alien RFID Reader</ReaderName>\n"
            + "  <ReaderType>Alien RFID Tag Reader, Model: ALR-9800(Four Antenna / Multi-Protocol / 915 Mhz)"
            + "</ReaderType>\n" + "  <IPAddress>" + asr.getCommandIP() + "</IPAddress>\n" + "  <CommandPort>"
            + asr.getCommandPort() + "</CommandPort>\n" + "  <HeartbeatTime>" + this.timeInMs / 1000
            + "</HeartbeatTime>\n" + "  <MACAddress>00:00:00:00:00:00</MACAddress>\n"
            + "</Alien-RFID-Reader-Heartbeat>\n";

    try {
        logger.debug("Attempting to send heartbeat...");
        DatagramSocket sock = new DatagramSocket(bindingPort);
        InetAddress ia = InetAddress.getByName(broadcastAddr);
        sock.setBroadcast(true);
        DatagramPacket p = new DatagramPacket(retString.getBytes(), retString.getBytes().length, ia,
                broadcastPort);
        sock.send(p);
        sock.disconnect();
        sock.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.BaseUDPSourceTest.java

private void doBasicTest(DatagramMode dataFormat, boolean enableEpoll, int numThreads) throws Exception {

    List<String> ports = NetworkUtils.getRandomPorts(2);
    final UDPSourceConfigBean conf = new UDPSourceConfigBean();

    conf.ports = ports;//  w w  w  . j a v  a2s  .  com
    conf.enableEpoll = enableEpoll;
    conf.numThreads = 1;
    conf.dataFormat = dataFormat;
    conf.maxWaitTime = 1000;
    conf.batchSize = 1000;
    conf.collectdCharset = UTF8;
    conf.syslogCharset = UTF8;
    conf.rawDataCharset = UTF8;

    try {
        byte[] bytes = null;
        switch (dataFormat) {
        case NETFLOW:
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(TEN_PACKETS_RESOURCE);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            is.close();
            baos.close();
            bytes = baos.toByteArray();
            break;
        case SYSLOG:
            bytes = RAW_SYSLOG_STR.getBytes(UTF8);

            conf.syslogCharset = UTF8;
            break;
        case RAW_DATA:
            bytes = StringUtils.join(RAW_DATA_VALUES, RAW_DATA_SEPARATOR).getBytes(UTF8);

            conf.rawDataSeparatorBytes = RAW_DATA_SEPARATOR;
            conf.rawDataOutputField = RAW_DATA_OUTPUT_FIELD;
            conf.rawDataCharset = UTF8;
            conf.rawDataMode = RawDataMode.CHARACTER;
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }

        initializeRunner(conf, numThreads);

        for (String port : ports) {
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress address = InetAddress.getLoopbackAddress();
            DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address,
                    Integer.parseInt(port));
            clientSocket.send(sendPacket);
            clientSocket.close();
        }

        runProduce(dataFormat, ports);

    } finally {
        destroyRunner();
    }
}

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

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);/* w  w  w. j  a  va 2 s .co  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()));
    packet.setPort(parameter.getPort());
    socket.send(packet);

    DatagramResponse response = new DatagramResponse(parameter.getResponseLength());
    DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length);
    socket.receive(responsePacket);
    response.setAddress(responsePacket.getAddress().getHostAddress());
    response.setPacketLength(responsePacket.getLength());
    socket.close();
    return response;
}

From source file:uk.me.sa.lightswitch.android.net.RequestMessage.java

private void sendMessageTo(byte[] message, String node) throws RemoteMessageException {
    try {// w w w.  ja v a2  s .c o m
        DatagramSocket s = new DatagramSocket();

        try {
            InetAddress[] addresses = InetAddress.getAllByName(node);
            List<IOException> failed = new ArrayList<IOException>(addresses.length);

            for (InetAddress address : addresses) {
                log.trace("Sending {} bytes to {}", message.length, address);

                try {
                    s.send(new DatagramPacket(message, message.length,
                            new InetSocketAddress(address, SERVICE)));
                } catch (IOException e) {
                    log.warn("Error sending datagram packet", e);
                    failed.add(e);
                }
            }

            if (addresses.length == 0) {
                log.error("No hosts to send to");
                throw new RemoteMessageException(new IllegalArgumentException("No hosts to send to"));
            } else if (failed.size() == addresses.length) {
                log.error("Error sending all datagram packets");
                throw new RemoteMessageException(failed.get(0));
            } else if (!failed.isEmpty()) {
                log.error("Error sending some (but not all) datagram packets");
            }
        } catch (UnknownHostException e) {
            log.error("Error resolving hostname", e);
            throw new RemoteMessageException(e);
        } catch (RuntimeException e) {
            log.error("Error sending request message", e);
            throw new RemoteMessageException(e);
        } finally {
            s.close();
        }
    } catch (SocketException e) {
        log.error("Error creating socket", e);
        throw new RemoteMessageException(e);
    }
}

From source file:org.openhab.binding.edimax.internal.UDPDiscoverer.java

private EdimaxDevice[] discover() throws SocketException, UnknownHostException, IOException {
    List<EdimaxDevice> discoveredDevices = new ArrayList<EdimaxDevice>();
    DatagramSocket serverSocket = null;
    try {//w  w  w  .ja v  a2s  . com
        serverSocket = new DatagramSocket(12346); // choose random port,
        // because with empty
        // port sometimes error
        // occures.

        // send UDP broadcast
        InetAddress ipAddress = InetAddress.getByName("255.255.255.255");
        byte[] sendData = DISCOVERY_BYTES;
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 20560);
        serverSocket.send(sendPacket);

        // receive
        serverSocket.setSoTimeout(1000 * 5);
        byte[] receiveData = new byte[1024];

        try {
            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());

                if (!StringUtils.isEmpty(sentence) && sentence.contains("EDIMAX")) {
                    byte[] mac = new byte[6];
                    System.arraycopy(receivePacket.getData(), 0, mac, 0, 6);

                    String encodedMAC = Hex.encodeHexString(mac).toUpperCase();
                    InetAddress discoveredIp = receivePacket.getAddress();

                    EdimaxDevice dev = new EdimaxDevice();
                    dev.setIp(discoveredIp.getHostAddress());
                    dev.setMac(encodedMAC);

                    discoveredDevices.add(dev);
                }

            }
        } catch (SocketTimeoutException e) {
            // intended to happen
        }
    } finally {
        if (serverSocket != null) {
            serverSocket.close();
        }
    }
    return discoveredDevices.toArray(new EdimaxDevice[discoveredDevices.size()]);
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Sends a wake-on-lan packet for specified MAC address across subnet
 * // w w w .  j  a  va2 s. c  om
 * @param macAddr
 *          the mac address to 'wake up'
 */
public static final void sendWakeOnLanPacket(String macAddr) {
    // Broadcast IP address
    final String IP = "255.255.255.255";
    final int port = 7;

    try {
        final byte[] MACBYTE = new byte[6];
        final String[] hex = macAddr.split("(\\:|\\-)");

        for (int i = 0; i < 6; i++) {
            MACBYTE[i] = (byte) Integer.parseInt(hex[i], 16);
        }
        final byte[] bytes = new byte[6 + 16 * MACBYTE.length];
        for (int i = 0; i < 6; i++) {
            bytes[i] = (byte) 0xff;
        }
        for (int i = 6; i < bytes.length; i += MACBYTE.length) {
            System.arraycopy(MACBYTE, 0, bytes, i, MACBYTE.length);
        }

        // Send UDP packet here
        final InetAddress address = InetAddress.getByName(IP);
        final DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
        final DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();

        LOGGER.info("Sent WOL packet to " + macAddr);
    } catch (final Exception e) {
        LOGGER.error("Error sending WOL packet to " + macAddr, e);
    }
}