Example usage for java.net DatagramPacket setSocketAddress

List of usage examples for java.net DatagramPacket setSocketAddress

Introduction

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

Prototype

public synchronized void setSocketAddress(SocketAddress address) 

Source Link

Document

Sets the SocketAddress (usually IP address + port number) of the remote host to which this datagram is being sent.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {//from   w ww.  ja v a2 s .  c o m

        int port = 80;

        DatagramSocket ds = new DatagramSocket(port);

        byte buffer[] = new byte[BUFSIZE];

        while (true) {

            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

            dp.setSocketAddress(InetSocketAddress.createUnresolved("google.com", 8080));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) {
    try {/*from   w w w  .  j ava2 s.  c o m*/

        int port = 80;

        DatagramSocket ds = new DatagramSocket(port);

        byte buffer[] = new byte[BUFSIZE];

        while (true) {

            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            // Receive data
            ds.receive(dp);
            // Display address from the datagram packet
            InetAddress ia = dp.getAddress();
            System.out.println(ia);

            dp.setSocketAddress(InetSocketAddress.createUnresolved("google.com", 8080));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

@Override
public void run() {
    if (parent.getRemote() == null) {
        throw new IllegalArgumentException("No user data set for remote user");
    }/*w w  w  .j  ava2 s.  com*/

    logger.info("Started listening to port: " + port);
    while (running && channel.isBound()) {

        byte[] bt = new byte[bufferSize];

        try {
            if (mode == ConnectionMode.BINDING) {
                logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - "
                        + channel.getPort());
                Thread.sleep(5); //No reason to hammer on this

                DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
                channel.receive(packet);
                SocketAddress currentSender = packet.getSocketAddress();

                sender = currentSender;
                byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());
                logger.info("Received data: " + Hex.encodeHexString(data) + " on "
                        + channel.getLocalSocketAddress() + " - " + channel.getPort());

                byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                        parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

                ByteBuffer outData = ByteBuffer.wrap(out);
                logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender);

                DatagramPacket pc = new DatagramPacket(out, 0, out.length);
                pc.setSocketAddress(sender);
                channel.send(pc);

                this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode
                logger.info("-> DTLS handshake");
            } else if (mode == ConnectionMode.HANDSHAKE) {
                Thread.sleep(5);
                logger.info("In handshake mode: ");

                if (transport == null) {
                    channel.connect(sender);

                    /**
                     * {@link NioUdpTransport} might replace the {@link UDPTransport} here.
                     * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a>
                     */
                    transport = serverProtocol.accept(dtlsServer,
                            new DtlsMuxStunTransport(parent, channel, MTU));
                }

                sctpService = new SCTPImpl(this);

                mode = ConnectionMode.TRANSFER;
                logger.info("-> SCTP mode");
            } else if (mode == ConnectionMode.TRANSFER) {

                /**
                 * Here we receive message and put them to a worker thread for handling
                 * If the output of handling the message is a message, then we send those
                 * using the same thread.
                 */
                byte[] buf = new byte[transport.getReceiveLimit()];
                int length = transport.receive(buf, 0, buf.length, waitMillis);
                if (length >= 0) {
                    byte[] handled = Arrays.copyOf(buf, length);
                    workPool.submit(() -> {
                        try {
                            List<byte[]> data = sctpService.handleRequest(handled);
                            data.forEach(this::putDataOnWire);
                        } catch (Exception e) {
                            logger.error("Failed handling message: ", e);
                        }
                    });
                    logger.debug("Input: " + Hex.encodeHexString(handled));
                }
            }
        } catch (Exception e) {
            logger.error("Com error:", e);
            logger.info("Shutting down, we cannot continue here");
            running = false; //Need to quit channel now
        }
    }
    workPool.shutdown();
}

From source file:org.necsave.NecsaveTransport.java

public void broadcast(Message msg) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ProtoOutputStream pos = new ProtoOutputStream(baos);
    msg.setMedium(MEDIUM.IP_BROADCAST);//w w w .jav  a2s.  c  om
    int length = msg.serialize(pos);
    DatagramPacket packet = new DatagramPacket(baos.toByteArray(), length);
    for (int i = 0; i < 3; i++)
        packet.setSocketAddress(new InetSocketAddress("255.255.255.255", broadcastPort + i));
    serverSocket.send(packet);
}

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

@SuppressWarnings("unchecked")
@Test//from w w w. ja  v a2s  .  c o  m
public void testUnicastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);
    //      SocketUtils.setLocalNicIfPossible(adapter);
    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));
    new DatagramSocket(SocketUtils.findAvailableUdpSocket()).send(packet);
    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
}

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

@SuppressWarnings("unchecked")
@Test//from  w  w w .ja v a 2s.  c om
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.springframework.integration.ip.udp.UdpChannelAdapterTests.java

@SuppressWarnings("unchecked")
@Test//from   w  ww. jav  a 2  s. co  m
@Ignore
public void testMulticastReceiver() throws Exception {
    QueueChannel channel = new QueueChannel(2);
    int port = SocketUtils.findAvailableUdpSocket();
    MulticastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter("225.6.7.8", port);
    adapter.setOutputChannel(channel);
    String nic = SocketTestUtils.chooseANic(true);
    if (nic == null) { // no multicast support
        LogFactory.getLog(this.getClass()).error("No Multicast support");
        return;
    }
    adapter.setLocalAddress(nic);
    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("225.6.7.8", port));
    new DatagramSocket(0, Inet4Address.getByName(nic)).send(packet);

    Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload()));
}

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

@Test
public void testUnicastReceiverException() throws Exception {
    SubscribableChannel channel = new DirectChannel();
    int port = SocketUtils.findAvailableUdpSocket();
    UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port);
    adapter.setOutputChannel(channel);//from  ww w .j a v a2 s  .com
    //      SocketUtils.setLocalNicIfPossible(adapter);
    adapter.setOutputChannel(channel);
    ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService());
    channel.subscribe(handler);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);
    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));
    new DatagramSocket(SocketUtils.findAvailableUdpSocket()).send(packet);
    Message<?> receivedMessage = errorChannel.receive(2000);
    assertNotNull(receivedMessage);
    assertEquals("Failed", ((Exception) receivedMessage.getPayload()).getCause().getMessage());
}

From source file:org.zxg.network.dhtcrawler.Crawler.java

@Override
protected void sendUdp(UdpMsg msg) throws IOException {
    DatagramPacket datagramPacket = new DatagramPacket(msg.data, msg.data.length);
    datagramPacket.setSocketAddress(new InetSocketAddress(msg.addr.ip, msg.addr.port));
    socket.send(datagramPacket);//  www.j  ava 2s  .c om
}