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.springframework.integration.syslog.inbound.SyslogReceivingChannelAdapterTests.java

@Test
public void testUdpRFC5424() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(
            SyslogReceivingChannelAdapterFactoryBean.Protocol.udp);
    int port = SocketUtils.findAvailableUdpSocket(1514);
    factory.setPort(port);/*w w w .  j ava 2  s. c  o m*/
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.setConverter(new RFC5424MessageConverter());
    factory.afterPropertiesSet();
    factory.start();
    UdpSyslogReceivingChannelAdapter adapter = (UdpSyslogReceivingChannelAdapter) factory.getObject();
    Thread.sleep(1000);
    byte[] buf = ("<14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - "
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]"
            + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance")
                    .getBytes("UTF-8");
    DatagramPacket packet = new DatagramPacket(buf, buf.length, new InetSocketAddress("localhost", port));
    DatagramSocket socket = new DatagramSocket();
    socket.send(packet);
    socket.close();
    @SuppressWarnings("unchecked")
    Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("loggregator", message.getPayload().get("syslog_HOST"));
    adapter.stop();
}

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

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;//  w w  w .j  a  v  a 2s .  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:com.navercorp.pinpoint.collector.receiver.thrift.udp.UDPReceiverTest.java

@Test
public void sendSocketBufferSize() throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(new byte[0], 0, 0);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(new InetSocketAddress(ADDRESS, PORT));

    datagramSocket.send(datagramPacket);
    datagramSocket.close();//w w  w.j  a  v  a  2s  .com
}

From source file:org.midonet.util.netty.TestServerFrontEndUPD.java

private DatagramPacket sendMSG(byte[] msg, int port) throws Exception {
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName("localhost");
    DatagramPacket sendPacket = new DatagramPacket(msg, msg.length, IPAddress, port);
    clientSocket.send(sendPacket);
    clientSocket.close();/*from w  w  w .ja v  a  2  s.c  om*/
    return sendPacket;
}

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

@Test
public void verifySendWithAck() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    byte[] buffer = new byte[1000];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort, true, true,
            "localhost", ackPort, 5000);
    handler.afterPropertiesSet();//  www . j a v a  2s .com
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                latch1.countDown();
                socket.receive(receivedPacket);
                socket.close();
                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("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    latch1.await(3000, TimeUnit.MILLISECONDS);
    String payload = "foobar";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    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));
    handler.shutDown();
}

From source file:org.graylog2.inputs.transports.UdpTransportTest.java

private void sendUdpDatagram(String hostname, int port, int size) throws IOException {
    final InetAddress address = InetAddress.getByName(hostname);
    final byte[] data = new byte[size];
    final DatagramPacket packet = new DatagramPacket(data, data.length, address, port);

    DatagramSocket toSocket = null;
    try {/*from ww  w. ja  v  a  2  s. com*/
        toSocket = new DatagramSocket();
        toSocket.send(packet);
    } finally {
        if (toSocket != null) {
            toSocket.close();
        }
    }
}

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

@Test
@Ignore//from   www  .java2 s .  c  o m
public void verifySendMulticastWithAcks() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch latch1 = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    Runnable catcher = new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[1000];
                DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
                MulticastSocket socket = new MulticastSocket(testPort);
                InetAddress group = InetAddress.getByName(multicastAddress);
                socket.joinGroup(group);
                latch1.countDown();
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
                socket.receive(receivedPacket);
                socket.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("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                noMulticast = true;
                latch1.countDown();
                e.printStackTrace();
            }
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    latch1.await(3000, TimeUnit.MILLISECONDS);
    if (noMulticast) {
        return;
    }
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", ackPort, 500000);
    handler.setMinAcksForSuccess(2);
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    handler.shutDown();
}

From source file:org.apache.axis2.transport.udp.UDPSender.java

@Override
public void sendMessage(MessageContext msgContext, String targetEPR, OutTransportInfo outTransportInfo)
        throws AxisFault {
    UDPOutTransportInfo udpOutInfo;//from  w  ww.j  a v  a 2 s  .  co m
    if ((targetEPR == null) && (outTransportInfo != null)) {
        // this can happen only at the server side and send the message using back chanel
        udpOutInfo = (UDPOutTransportInfo) outTransportInfo;
    } else {
        udpOutInfo = new UDPOutTransportInfo(targetEPR);
    }
    MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    format.setContentType(udpOutInfo.getContentType());
    byte[] payload = messageFormatter.getBytes(msgContext, format);
    try {
        DatagramSocket socket = new DatagramSocket();
        if (log.isDebugEnabled()) {
            log.debug("Sending " + payload.length + " bytes to " + udpOutInfo.getAddress());
        }
        try {
            socket.send(new DatagramPacket(payload, payload.length, udpOutInfo.getAddress()));
            if (!msgContext.getOptions().isUseSeparateListener() && !msgContext.isServerSide()) {
                waitForReply(msgContext, socket, udpOutInfo.getContentType());
            }
        } finally {
            socket.close();
        }
    } catch (IOException ex) {
        throw new AxisFault("Unable to send packet", ex);
    }
}

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

@SuppressWarnings("unchecked")
@Test//from w  ww . ja  va2 s  . com
public void testUnicastReceiverWithReply() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    adapter.start();
    SocketTestUtils.waitListening(adapter);

    Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build();
    DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
    DatagramPacket packet = mapper.fromMessage(message);
    packet.setSocketAddress(new InetSocketAddress("localhost", port));
    final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket());
    socket.send(packet);
    final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>();
    final CountDownLatch receiverReadyLatch = new CountDownLatch(1);
    final CountDownLatch replyReceivedLatch = new CountDownLatch(1);
    //main thread sends the reply using the headers, this thread will receive it
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            DatagramPacket answer = new DatagramPacket(new byte[2000], 2000);
            try {
                receiverReadyLatch.countDown();
                socket.receive(answer);
                theAnswer.set(answer);
                replyReceivedLatch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
    String replyString = "reply:" + System.currentTimeMillis();
    byte[] replyBytes = replyString.getBytes();
    DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length);
    reply.setSocketAddress(
            new InetSocketAddress((String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS),
                    (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT)));
    assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS));
    new DatagramSocket().send(reply);
    assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS));
    DatagramPacket answerPacket = theAnswer.get();
    assertNotNull(answerPacket);
    assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength()));
}

From source file:org.apache.camel.component.mina.MinaUdpWithInOutUsingPlainSocketTest.java

private String sendAndReceiveUdpMessages(String input) throws Exception {
    DatagramSocket socket = new DatagramSocket();
    InetAddress address = InetAddress.getByName("127.0.0.1");

    byte[] data = input.getBytes();

    DatagramPacket packet = new DatagramPacket(data, data.length, address, PORT);
    LOG.debug("+++ Sending data +++");
    socket.send(packet);

    Thread.sleep(1000);/*from  w  w  w .ja v a2s.co m*/

    byte[] buf = new byte[128];
    DatagramPacket receive = new DatagramPacket(buf, buf.length, address, PORT);
    LOG.debug("+++ Receving data +++");
    socket.receive(receive);

    socket.close();

    return new String(receive.getData(), 0, receive.getLength());
}