Example usage for java.net DatagramPacket DatagramPacket

List of usage examples for java.net DatagramPacket DatagramPacket

Introduction

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

Prototype

public DatagramPacket(byte buf[], int length) 

Source Link

Document

Constructs a DatagramPacket for receiving packets of length length .

Usage

From source file:com.kecso.socket.ServerSocketControl.java

@Override
public void run() {
    DatagramSocket sock = null;//from   ww  w  . j a v  a2s .com

    try {
        sock = new DatagramSocket(8888);
        sock.setSoTimeout(1000);

        byte[] buffer = new byte[65536];
        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

        while (!Thread.currentThread().isInterrupted()) {
            try {
                sock.receive(incoming);
                byte[] data = incoming.getData();
                this.udpMessage = SerializationUtils.deserialize(data);

                byte[] response = SerializationUtils.serialize(
                        this.output != null
                                ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(),
                                        (float) output.getAltitude(), (float) output.getRpm())
                                : null);
                DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(),
                        incoming.getPort());
                sock.send(dp);
            } catch (SocketTimeoutException e) {
            }
        }
    } catch (Exception e) {
        System.err.println("IOException " + e);
    } finally {
        if (sock != null) {
            sock.close();
        }

    }
}

From source file:com.wmfsystem.eurekaserver.broadcast.Server.java

public void run() {
    try {//from   w  w  w  .  j av  a2 s.  co  m
        socket = new DatagramSocket(DEFAULT_PORT);
    } catch (Exception ex) {
        System.out.println("Problem creating socket on port: " + DEFAULT_PORT);
    }

    packet = new DatagramPacket(new byte[1], 1);

    while (true) {
        try {
            socket.receive(packet);
            System.out.println("Received from: " + packet.getAddress() + ":" + packet.getPort());
            byte[] outBuffer = new java.util.Date().toString().getBytes();
            packet.setData(outBuffer);
            packet.setLength(outBuffer.length);
            socket.setBroadcast(true);
            socket.send(packet);

            Set<InetAddress> localAddress = getLocalAddress();

            Set<String> ips = localAddress.stream().map(ad -> ad.getHostAddress()).collect(Collectors.toSet())
                    .stream().sorted().collect(Collectors.toSet());

            RestTemplate template = new RestTemplate();

            ips.forEach(ip -> {
                template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                        HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                try {
                    template.exchange("http://" + packet.getAddress().getHostAddress().concat(":8000?ip={ip}"),
                            HttpMethod.GET, HttpEntity.EMPTY, Void.class, ip.concat(":8000"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            System.out.println("Message ----> " + packet.getAddress().getHostAddress());

        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}

From source file:werewolf.client.DatagramReceiverThread.java

public DatagramReceiverThread(int listenPort) {
    buf = new byte[4096];
    packet = new DatagramPacket(buf, buf.length);
    this.listenPort = listenPort;

    try {// w w  w .j a v  a  2  s .  c o m
        socket = new DatagramSocket(listenPort);
    } catch (SocketException ex) {
        Logger.getLogger(DatagramReceiverThread.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

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

    socket.setReuseAddress(true);/*from  w  w  w  . j  a v a  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()));
    if (parameter.getPort() > 0)
        packet.setPort(parameter.getPort());
    socket.send(packet);
    socket.close();
    return null;
}

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

public DatagramResponse execute(DatagramParameter parameter) throws IOException {
    DatagramSocket socket = new DatagramSocket(null);
    socket.setReuseAddress(true);// w ww  .  j av a2  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()));
    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:org.vesalainen.net.sntp.SNTPServer.java

@Override
public void run() {
    try {/*from w  ww  . j a v  a  2  s .co m*/
        DatagramSocket socket = new DatagramSocket(123);
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        while (true) {
            socket.receive(packet);
            NtpV3Impl msg = new NtpV3Impl();
            msg.setDatagramPacket(packet);
            System.err.println(msg);
        }
    } catch (SocketException ex) {
        Logger.getLogger(SNTPServer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SNTPServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.eredlab.g4.ccl.net.DiscardUDPClient.java

public DiscardUDPClient() {
    _sendPacket = new DatagramPacket(new byte[0], 0);
}

From source file:com.esri.geoevent.test.performance.ClockSync.java

@Override
public void run() {
    DatagramSocket socket = null;
    try {/* w  ww .  j  ava 2  s.c om*/
        byte[] incomingBuffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length);

        ByteBuffer bb = ByteBuffer.allocate(8);
        DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port);
        socket = new DatagramSocket(port);
        socket.setSoTimeout(100);
        while (isRunning.get()) {
            try {
                socket.receive(packet);
                long now = System.currentTimeMillis();
                bb.putLong(now);
                outgoingPacket.setAddress(packet.getAddress());
                outgoingPacket.setPort(packet.getPort());
                socket.send(outgoingPacket);
                bb.clear();
                //System.out.println("Sent the time " + now);
            } catch (SocketTimeoutException ex) {
                // Do nothing if nothing was sent.
            }
        }
    } catch (BindException e) {
        // port is in use - increment and try again
        port++;
        this.run();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(socket);
    }
}

From source file:werewolf_client.Werewolf_Client.java

public void recvFromClient(String adr, int p) throws SocketException, IOException {
    DatagramSocket recv = new DatagramSocket(p);
    byte[] recvData = new byte[1024];

    while (true) {
        DatagramPacket recvPacket = new DatagramPacket(recvData, recvData.length);
        recv.receive(recvPacket);/*from w w w  . jav a  2 s.  c  om*/

        String s = new String(recvPacket.getData(), 0, recvPacket.getLength());
        System.out.println("ReceivedD\n" + s);
    }
}

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

@Test
public void verifySend() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    byte[] buffer = new byte[8];
    final DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
    final CountDownLatch latch = new CountDownLatch(1);
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        public void run() {
            try {
                DatagramSocket socket = new DatagramSocket(testPort);
                socket.receive(receivedPacket);
                latch.countDown();/* ww w.ja v a  2 s .c o m*/
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    Thread.sleep(1000);
    UnicastSendingMessageHandler handler = new UnicastSendingMessageHandler("localhost", testPort);
    String payload = "foo";
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch.await(3000, TimeUnit.MILLISECONDS));
    byte[] src = receivedPacket.getData();
    int length = receivedPacket.getLength();
    int offset = receivedPacket.getOffset();
    byte[] dest = new byte[length];
    System.arraycopy(src, offset, dest, 0, length);
    assertEquals(payload, new String(dest));
    handler.shutDown();
}