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:org.parakoopa.udphp.mediator.Mediator.java

public Mediator() {
    try {// www.  j  ava2 s  .  c  o m
        //Set up some local variables
        server = new ServerSocket(port);
        server_udp = new DatagramSocket(port);
        serverMap = new HashMap();
        clientMap = new HashMap();
        final Mediator me = this;

        Mediator.log("UDPHP STARTED", false);
        Mediator.log("Starting UDP and TCP servers on port " + port, false);

        //Start two new threads for the servers, just to be on the safe side.
        new Thread() {
            @Override
            //START UDP SERVER
            public void run() {
                Mediator.log("-> UDP: Loaded UDP Listener", true);
                //When packet is processed: Continue with next packet
                while (true) {
                    try {
                        //Create incoming packet and wait for it.
                        DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
                        server_udp.receive(packet);
                        //When a packet arrivied: Deal with it. 
                        UDPPacket packetHandler = new UDPPacket(me, packet, server_udp);
                        //This was once also a seperate thread, that's why the method is called run.
                        //annother thread is not needed though.
                        //it is propably even more efficient to just swap the packet out instead of
                        //creating a new class above. Do what you want :)
                        packetHandler.run();
                    } catch (IOException ex) {
                        //Print all exceptions.
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            @Override
            //START TCP SERVER
            public void run() {
                Mediator.log("-> TCP: Loaded TCP Listener", true);
                //When connection thread is created: Wait for next connection
                while (true) {
                    try {
                        //Wait for connection
                        Socket client = server.accept();
                        //When connection is opened: Start thread that handles it.
                        TCPConnection connectionHandler = new TCPConnection(me, client, server);
                        new Thread(connectionHandler).start();
                    } catch (IOException ex) {
                        //Print all exceptions.
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
    } catch (IOException ex) {
        //Print all exceptions.
        ex.printStackTrace();
    }
}

From source file:org.apache.catalina.cluster.mcast.McastServiceImpl.java

/**
 * Create a new mcast service impl//  w  w  w .j  av  a2s.  co m
 * @param member - the local member
 * @param sendFrequency - the time (ms) in between pings sent out
 * @param expireTime - the time (ms) for a member to expire
 * @param port - the mcast port
 * @param bind - the bind address (not sure this is used yet)
 * @param mcastAddress - the mcast address
 * @param service - the callback service
 * @throws IOException
 */
public McastServiceImpl(McastMember member, long sendFrequency, long expireTime, int port, InetAddress bind,
        InetAddress mcastAddress, MembershipListener service) throws IOException {
    if (bind != null)
        socket = new MulticastSocket(new java.net.InetSocketAddress(bind, port));
    else
        socket = new MulticastSocket(port);
    this.member = member;
    address = mcastAddress;
    this.port = port;
    sendPacket = new DatagramPacket(new byte[1000], 1000);
    sendPacket.setAddress(address);
    sendPacket.setPort(port);
    receivePacket = new DatagramPacket(new byte[1000], 1000);
    receivePacket.setAddress(address);
    receivePacket.setPort(port);
    membership = new McastMembership(member.getName());
    timeToExpiration = expireTime;
    this.service = service;
    this.sendFrequency = sendFrequency;
}

From source file:net.sbbi.upnp.DiscoveryListener.java

private void startMultiCastSocket() throws IOException {
    int bindPort = Discovery.DEFAULT_SSDP_SEARCH_PORT;
    String port = System.getProperty("net.sbbi.upnp.Discovery.bindPort");
    if (port != null) {
        bindPort = Integer.parseInt(port);
    }//  w w  w . j a v  a2s  .c o  m

    skt = new java.net.MulticastSocket(null);
    skt.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), bindPort));
    skt.setTimeToLive(Discovery.DEFAULT_TTL);
    skt.setSoTimeout(DEFAULT_TIMEOUT);
    skt.joinGroup(InetAddress.getByName(Discovery.SSDP_IP));

    byte[] buf = new byte[2048];
    input = new DatagramPacket(buf, buf.length);

}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.uplink.UplinkReceiver.java

/**
 * Run the relay server.//  w  w  w. j  a  v a 2s  . c om
 */
@Override
public void run() {
    initRelayServers();
    RelayServer me = this.relayServers.getMe();

    this.databaseLoggerTimer.init();
    this.expireNodesTimer.init();

    byte[] receiveBuffer = new byte[BUFFERSIZE];
    DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);

    while (this.run.get()) {
        try {
            this.sock.receive(packet);
            try {
                if (this.packetHandler.processPacket(me, packet)) {
                    this.relayClusterSender.addPacket(me, packet);
                    this.distributor.signalUpdate();
                    this.databaseLogger.log(this.logger, Level.DEBUG);
                }
            } catch (Throwable e) {
                this.logger.error(e);
            }
        } catch (Exception e) {
            if (!SocketException.class.equals(e.getClass())) {
                e.printStackTrace();
            }
        }
    }

    if (this.sock != null) {
        this.sock.close();
        this.sock = null;
    }
}

From source file:org.openacs.HostsBean.java

public void RequestConnectionUDP(String url, String user, String pass) throws Exception {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);// w  w w.  ja v  a 2 s .co m
    s.bind(new InetSocketAddress(Application.getSTUNport()));
    String ts = Long.toString(Calendar.getInstance().getTimeInMillis());
    String id = ts;
    Random rnd = new Random();
    byte[] nonceArray = new byte[16];
    rnd.nextBytes(nonceArray);

    String cn = cvtHex.cvtHex(nonceArray);
    url = url.substring(6);
    String[] u = url.split(":");

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    String data = ts + id + user + cn;
    byte[] rawHmac = mac.doFinal(data.getBytes());
    String signature = cvtHex.cvtHex(rawHmac);
    String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig="
            + signature + " HTTP/1.1\r\n\r\n";

    byte[] breq = req.getBytes();
    DatagramPacket packet = new DatagramPacket(breq, breq.length);
    packet.setAddress(InetAddress.getByName(u[0]));
    packet.setPort(Integer.parseInt(u[1]));
    s.send(packet);
}

From source file:edu.hawaii.soest.kilonalu.adam.AdamDispatcher.java

/**
 * A method that executes the streaming of data from the source to the RBNB
 * server after all configuration of settings, connections to hosts, and
 * thread initiatizing occurs.  This method contains the detailed code for 
 * streaming the data and interpreting the stream.
 *//* www . j  ava  2  s . co m*/
protected boolean execute() {
    logger.info("AdamDispatcher.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    // while data are being sent, read them into the buffer
    try {

        // Create a buffer that will store the sample bytes as they are read
        byte[] bufferArray = new byte[getBufferSize()];

        // and a ByteBuffer used to transfer the bytes to the parser
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        this.datagramPacket = new DatagramPacket(bufferArray, bufferArray.length);

        // while there are bytes to read from the socket ...
        while (!failed) {

            // receive any incoming UDP packets and parse the data payload
            datagramSocket.receive(this.datagramPacket);

            logger.debug("Host: " + datagramPacket.getAddress() + " data: "
                    + new String(Hex.encodeHex(datagramPacket.getData())));

            // the address seems to be returned with a leading slash (/). Trim it.
            String datagramAddress = datagramPacket.getAddress().toString().replaceAll("/", "");

            sampleBuffer.put(datagramPacket.getData());

            // Given the IP address of the source UDP packet and the data ByteBuffer,
            // find the correct source in the sourceMap hash and process the data
            if (sourceMap.get(datagramAddress) != null) {

                AdamSource source = sourceMap.get(datagramAddress);

                // process the data using the AdamSource driver
                source.process(datagramAddress, this.xmlConfiguration, sampleBuffer);

            } else {
                logger.debug("There is no configuration information for " + "the ADAM module at "
                        + datagramAddress + ". Please add the configuration to the "
                        + "sensor.properties.xml configuration file.");
            }

            sampleBuffer.clear();

        } // end while (more socket bytes to read)

        disconnect();
        //      
    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        e.printStackTrace();
        return !failed;

    }

    return !failed;
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public void startListener() {
    listeningExecutorService.submit(new Runnable() {

        private final int incomingBufferSize = 1024; //TODO check this

        @Override//w w  w  .  jav a  2 s.co  m
        public void run() {
            try {
                if (datagramSocket == null || datagramSocket.isClosed()) {
                    datagramSocket = new DatagramSocket(UDP_PORT, InetAddress.getByName("0.0.0.0"));
                    logger.info("opening upd socket {}", datagramSocket.getLocalSocketAddress());
                }
                final DatagramPacket datagramPacket = new DatagramPacket(new byte[incomingBufferSize],
                        incomingBufferSize);
                logger.trace("waiting for message on socket addr = {}", datagramSocket.getLocalSocketAddress());
                isListening = true;
                datagramSocket.receive(datagramPacket);
                processingExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final String sourceAddress = datagramPacket.getAddress().getHostAddress();
                            ByteBuffer byteBuffer = ByteBuffer.wrap(datagramPacket.getData(),
                                    datagramPacket.getOffset(), datagramPacket.getLength());
                            int magic = byteBuffer.getInt(); //4 bytes
                            checkArgument(magic == MAGIC, "magic mismatch, expected %s, got %s", MAGIC, magic);
                            final LocalDiscoveryProtos.Announce announce = LocalDiscoveryProtos.Announce
                                    .parseFrom(ByteString.copyFrom(byteBuffer));
                            final String deviceId = hashDataToDeviceIdString(announce.getId().toByteArray());
                            if (!equal(deviceId, configuration.getDeviceId())) {
                                //                                logger.debug("received local announce from device id = {}", deviceId);
                                final List<DeviceAddress> deviceAddresses = Lists
                                        .newArrayList(Iterables.transform(
                                                firstNonNull(announce.getAddressesList(),
                                                        Collections.<String>emptyList()),
                                                new Function<String, DeviceAddress>() {
                                                    @Override
                                                    public DeviceAddress apply(String address) {
                                                        //                                /*
                                                        //                                When interpreting addresses with an unspecified address, e.g., tcp://0.0.0.0:22000 or tcp://:42424, the source address of the discovery announcement is to be used.
                                                        //                                 */
                                                        return DeviceAddress.newBuilder()
                                                                .setAddress(address.replaceFirst(
                                                                        "tcp://(0.0.0.0|):",
                                                                        "tcp://" + sourceAddress + ":"))
                                                                .setDeviceId(deviceId)
                                                                .setInstanceId(announce.getInstanceId())
                                                                .setProducer(
                                                                        DeviceAddress.AddressProducer.LOCAL_DISCOVERY)
                                                                .build();
                                                    }
                                                }));
                                boolean isNew = false;
                                synchronized (localDiscoveryRecords) {
                                    isNew = !localDiscoveryRecords.removeAll(deviceId).isEmpty();
                                    localDiscoveryRecords.putAll(deviceId, deviceAddresses);
                                }
                                eventBus.post(new MessageReceivedEvent() {
                                    @Override
                                    public List<DeviceAddress> getDeviceAddresses() {
                                        return Collections.unmodifiableList(deviceAddresses);
                                    }

                                    @Override
                                    public String getDeviceId() {
                                        return deviceId;
                                    }
                                });
                                if (isNew) {
                                    eventBus.post(new NewLocalPeerEvent() {
                                        @Override
                                        public String getDeviceId() {
                                            return deviceId;
                                        }
                                    });
                                }
                            }
                        } catch (Exception ex) {
                            logger.warn("error processing datagram", ex);
                        }
                    }
                });
                listeningExecutorService.submit(this);
            } catch (Exception ex) {
                isListening = false;
                if (listeningExecutorService.isShutdown()) {
                    return;
                }
                if (datagramSocket != null) {
                    logger.warn("error receiving datagram", ex);
                    listeningExecutorService.submit(this);
                } else if (ex instanceof java.net.BindException) {
                    logger.warn("error opening udp server socket : {}", ex.toString());
                } else {
                    logger.warn("error opening udp server socket", ex);
                }
            }
        }
    });
}

From source file:org.parakoopa.gmnetgate.punch.Mediator.java

public Mediator() {
    try {/*from  w  ww  .  j  a v a2 s.  co  m*/
        //Set up some local variables
        server = new ServerSocket(port);
        server_udp = new DatagramSocket(port);
        serverMap = new HashMap();
        clientMap = new HashMap();
        final Mediator me = this;

        Mediator.log("GMnet GATE.PUNCH STARTED", false);
        Mediator.log("Starting UDP and TCP servers on port " + port, false);

        //Start two new threads for the servers, just to be on the safe side.
        new Thread() {
            @Override
            //START UDP SERVER
            public void run() {
                Mediator.log("Loaded UDP Listener", true);
                //When packet is processed: Continue with next packet
                while (true) {
                    try {
                        //Create incoming packet and wait for it.
                        DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
                        server_udp.receive(packet);
                        //When a packet arrivied: Deal with it. 
                        UDPPacket packetHandler = new UDPPacket(me, packet, server_udp);
                        //This was once also a seperate thread, that's why the method is called run.
                        //annother thread is not needed though.
                        //it is propably even more efficient to just swap the packet out instead of
                        //creating a new class above. Do what you want :)
                        packetHandler.run();
                    } catch (IOException ex) {
                        //Print all exceptions.
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread() {
            @Override
            //START TCP SERVER
            public void run() {
                Mediator.log("Loaded TCP Listener", true);
                //When connection thread is created: Wait for next connection
                while (true) {
                    try {
                        //Wait for connection
                        Socket client = server.accept();
                        //When connection is opened: Start thread that handles it.
                        TCPConnection connectionHandler = new TCPConnection(me, client, server);
                        new Thread(connectionHandler).start();
                    } catch (IOException ex) {
                        //Print all exceptions.
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
        if (Mediator.dbg_servers) {
            for (int i = 0; i < 50; i++) {
                Server serverObj = this.getServer(UUID.randomUUID().toString());
                serverObj.setData1(UUID.randomUUID().toString());
                serverObj.setData2(UUID.randomUUID().toString());
                serverObj.setData3(UUID.randomUUID().toString());
                serverObj.setData4(UUID.randomUUID().toString());
                serverObj.setData5(UUID.randomUUID().toString());
                serverObj.setData6(UUID.randomUUID().toString());
                serverObj.setData7(UUID.randomUUID().toString());
                serverObj.setData8(UUID.randomUUID().toString());
            }
        }
    } catch (IOException ex) {
        //Print all exceptions.
        ex.printStackTrace();
    }
}

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

@Test
@Ignore//from   w  w w .j a  va2 s.c  om
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.catalina.cluster.mcast.McastServiceImpl.java

/**
 * Send a ping// w  ww .  ja  va2s.co m
 * @throws Exception
 */
public void send() throws Exception {
    member.inc();
    byte[] data = member.getData(this.serviceStartTime);
    DatagramPacket p = new DatagramPacket(data, data.length);
    p.setAddress(address);
    p.setPort(port);
    socket.send(p);
}