Example usage for java.net DatagramSocket DatagramSocket

List of usage examples for java.net DatagramSocket DatagramSocket

Introduction

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

Prototype

public DatagramSocket() throws SocketException 

Source Link

Document

Constructs a datagram socket and binds it to any available port on the local host machine.

Usage

From source file:org.apache.nifi.processors.standard.TestListenUDP.java

@Test
public void testBatchingSingleSender() throws IOException, InterruptedException {
    final String delimiter = "NN";
    runner.setProperty(ListenUDP.MESSAGE_DELIMITER, delimiter);
    runner.setProperty(ListenUDP.MAX_BATCH_SIZE, "3");

    final List<String> messages = getMessages(5);
    final int expectedQueued = messages.size();
    final int expectedTransferred = 2;

    run(new DatagramSocket(), messages, expectedQueued, expectedTransferred);
    runner.assertAllFlowFilesTransferred(ListenUDP.REL_SUCCESS, expectedTransferred);

    List<MockFlowFile> mockFlowFiles = runner.getFlowFilesForRelationship(ListenUDP.REL_SUCCESS);

    MockFlowFile mockFlowFile1 = mockFlowFiles.get(0);
    mockFlowFile1.assertContentEquals(//  w ww  . j av  a 2  s. co m
            "This is message 1" + delimiter + "This is message 2" + delimiter + "This is message 3");

    MockFlowFile mockFlowFile2 = mockFlowFiles.get(1);
    mockFlowFile2.assertContentEquals("This is message 4" + delimiter + "This is message 5");

    verifyProvenance(expectedTransferred);
}

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

@Test
public void datagramPacket_length_zero() {
    UDPReceiver receiver = null;//www  .  ja  v  a  2 s. 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: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  .  j  av a  2  s .  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: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);//from   w ww.j av  a  2s. c o  m
    clientSocket.send(sendPacket);
}

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();/*  www  .  j  a  v a2s. co  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:Network.Network.java

private String discoverUDPServer() {
    DatagramSocket c;// w  ww.j  ava  2 s  .  c  o m

    String foundIP = null;
    // Find the server using UDP broadcast
    try {
        //Open a random port to send the package
        c = new DatagramSocket();
        c.setBroadcast(true);

        byte[] sendData = "DISCOVER_BATTLESHIPSERVER_REQUEST".getBytes();

        //Try the 255.255.255.255 first
        try {
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("255.255.255.255"), 8888);
            c.send(sendPacket);
            System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)");
        } catch (Exception e) {
        }

        /*// Broadcast the message over all the network interfaces
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
                
        if (networkInterface.isLoopback() || !networkInterface.isUp()) {
            continue; // Don't want to broadcast to the loopback interface
        }
                
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress broadcast = interfaceAddress.getBroadcast();
            if (broadcast == null) {
                continue;
            }
                
            // Send the broadcast package!
            try {
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888);
                c.send(sendPacket);
            } 
            catch (Exception e) {
            }
                
            System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
        }
        }*/

        System.out.println(getClass().getName()
                + ">>> Done looping over all network interfaces. Now waiting for a reply!");

        //Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        c.receive(receivePacket);

        //We have a response
        System.out.println(getClass().getName() + ">>> Broadcast response from server: "
                + receivePacket.getAddress().getHostAddress());

        //Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.equals("DISCOVER_BATTLESHIPSERVER_RESPONSE")) {
            //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller)
            foundIP = receivePacket.getAddress().getHostAddress();
        }

        //Close the port!
        c.close();
    } catch (IOException ex) {
        Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
    }
    return foundIP;
}

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.  jav a  2s  .c  om
    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:com.cloudera.flume.reporter.ganglia.GangliaSink.java

@Override
public void open() throws IOException {
    // TODO (jon) need to worry about SecurityException and other
    // RuntimeExceptions.

    // From o.a.h.metrics.spi.Util
    // This can throw IllegalArgumentException or SecurityException
    metricsServers = Util.parse(servers, DEFAULT_PORT);

    try {//ww w .  j av a2  s . c  om
        datagramSocket = new DatagramSocket();
    } catch (SocketException se) {
        LOG.warn("problem with ganglia socket", se);
    }

}

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;//ww w  .  j  a v  a  2 s.  c  o m
    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:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public Future sendAnnounceMessage() {
    return processingExecutorService.submit(new Callable() {

        @Override//from ww  w  .ja v a 2s  .  c  o  m
        public Object call() throws Exception {
            for (int i = 0; i < 10 && !isListening; i++) { //wait for listening
                Thread.sleep(100);
            }
            if (!isListening) {
                logger.warn("skipping announce message, udp listening is not active");
                return null;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            new DataOutputStream(out).writeInt(MAGIC);
            Announce.newBuilder()
                    .setId(ByteString.copyFrom(deviceIdStringToHashData(configuration.getDeviceId())))
                    .setInstanceId(configuration.getInstanceId()).build().writeTo(out);
            byte[] data = out.toByteArray();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    InetAddress broadcastAddress = interfaceAddress.getBroadcast();
                    logger.trace("interface = {} address = {} broadcast = {}", networkInterface,
                            interfaceAddress, broadcastAddress);
                    if (broadcastAddress != null) {
                        logger.debug("sending broadcast announce on {}", broadcastAddress);
                        try (DatagramSocket broadcastSocket = new DatagramSocket()) {
                            broadcastSocket.setBroadcast(true);
                            DatagramPacket datagramPacket = new DatagramPacket(data, data.length,
                                    broadcastAddress, UDP_PORT);
                            broadcastSocket.send(datagramPacket);
                        } catch (Exception ex) {
                            logger.warn("error sending datagram", ex);
                        }
                    }
                }
            }
            return null;
        }
    });
}