Example usage for java.net DatagramPacket getLength

List of usage examples for java.net DatagramPacket getLength

Introduction

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

Prototype

public synchronized int getLength() 

Source Link

Document

Returns the length of the data to be sent or the length of the data received.

Usage

From source file:org.dragonet.net.inf.mcpe.NetworkHandler.java

private void processPacket(DatagramPacket packet) {
    try {/*from ww  w . j  a va2s.  c om*/
        PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData()));
        int raknetPID = reader.readByte() & 0xFF;
        switch (raknetPID) {
        case RaknetConstants.ID_PING_OPEN_CONNECTIONS:
            ServerInfoPacket pkReply = new ServerInfoPacket();
            pkReply.time = reader.readLong();
            pkReply.serverID = serverID;
            pkReply.serverName = this.getManager().getServer().getServer().getName();
            pkReply.encode();
            this.udp.send(pkReply.getData(), packet.getSocketAddress());
            break;
        case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1:
            reader.read(16); //MAGIC
            reader.readByte(); //RakNet Protocol
            short mtu = (short) ((packet.getLength() - 18) & 0xFFFF);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PEBinaryWriter writer = new PEBinaryWriter(bos);
            writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1);
            writer.write(RaknetConstants.magic);
            writer.writeLong(NetworkHandler.serverID);
            writer.writeByte((byte) 0x00);
            writer.writeShort(mtu);
            this.udp.send(bos.toByteArray(), packet.getSocketAddress());
            break;
        case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2:
            reader.read(16);
            reader.readByte();
            reader.readInt();
            reader.readShort();
            short clientMTU = reader.readShort();
            long clientID = reader.readLong();
            ByteArrayOutputStream bos8 = new ByteArrayOutputStream();
            PEBinaryWriter writer8 = new PEBinaryWriter(bos8);
            writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2);
            writer8.write(RaknetConstants.magic);
            writer8.writeLong(NetworkHandler.serverID);
            writer8.writeAddress(packet.getAddress(), (short) packet.getPort());
            writer8.writeShort(clientMTU);
            writer8.writeByte((byte) 0x00);
            this.send(bos8.toByteArray(), packet.getSocketAddress());
            PENetworkClient session = new PENetworkClient(this, packet.getSocketAddress(), clientID, clientMTU);
            clients.put(packet.getSocketAddress().toString(), session);
            //this.server.getServer().getSessionRegistry().add(session);
            break;
        case 0x80:
        case 0x81:
        case 0x82:
        case 0x83:
        case 0x84:
        case 0x85:
        case 0x86:
        case 0x87:
        case 0x88:
        case 0x89:
        case 0x8A:
        case 0x8B:
        case 0x8C:
        case 0x8D:
        case 0x8E:
        case 0x8F:
            if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                RaknetDataPacket dataPacket = new RaknetDataPacket(
                        ArrayUtils.subarray(packet.getData(), 1, packet.getLength()));
                dataPacket.decode();
                clients.get(getClientKey(packet.getSocketAddress())).processDataPacket(dataPacket);
            }
            break;
        case 0xC0:
            if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                clients.get(getClientKey(packet.getSocketAddress()))
                        .processACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length));
            }
            break;
        case 0xA0:
            if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) {
                clients.get(getClientKey(packet.getSocketAddress()))
                        .processNACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length));
            }
            break;
        }
    } catch (IOException e) {
    }
}

From source file:org.echocat.jomon.net.dns.DnsServer.java

public void serveUDP(InetSocketAddress address) {
    try {/*from   www  .  j  a  va  2 s .c om*/
        final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress());
        synchronized (_closeables) {
            _closeables.add(sock);
        }
        final short udpLength = 512;
        final byte[] in = new byte[udpLength];
        final DatagramPacket indp = new DatagramPacket(in, in.length);
        DatagramPacket outdp = null;
        while (!currentThread().isInterrupted()) {
            indp.setLength(in.length);
            receive(sock, indp);
            final Message query;
            byte[] response;
            try {
                query = new Message(in);
                response = generateReply(query, in, indp.getLength(), null);
                if (response == null) {
                    continue;
                }
            } catch (final IOException ignored) {
                response = formerrMessage(in);
            }
            if (outdp == null) {
                outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort());
            } else {
                outdp.setData(response);
                outdp.setLength(response.length);
                outdp.setAddress(indp.getAddress());
                outdp.setPort(indp.getPort());
            }
            sock.send(outdp);
        }
    } catch (final InterruptedIOException ignored) {
        currentThread().interrupt();
    } catch (final IOException e) {
        LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e);
    }
}

From source file:org.saintandreas.serket.ssdp.Message.java

public static Message parseMessage(DatagramPacket packet) throws IOException, HttpException {
    Type type;/* w  w  w .  j  a  va2  s. c o m*/
    Map<String, Header> headers = new HashMap<String, Header>();
    String usn = null;

    LineParser parser = new BasicLineParser();
    SessionInputBuffer inBuffer = new ByteArrayInputBuffer(packet.getData());
    String command = inBuffer.readLine();
    Header[] hs = AbstractMessageParser.parseHeaders(inBuffer, 64, 1024, parser);
    for (Header h : hs) {
        headers.put(h.getName(), h);
    }

    if (Message.NOTIFY_START.startsWith(command)) {
        Header h = headers.get("NTS");
        usn = headers.get("USN").getValue();
        if ("ssdp:alive".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message alive " + usn);
            type = Type.NOTIFY_ALIVE;
        } else if ("ssdp:update".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message update " + usn);
            type = Type.NOTIFY_UPDATE;
        } else if ("ssdp:byebye".equals(h.getValue())) {
            // LogFactory.getLog(SSDPTests.class).debug("Notify message byebye " + usn);
            type = Type.NOTIFY_BYEBYE;
        } else
            throw new RuntimeException("unknown type");
    } else if (Message.SEARCH_START.startsWith(command)) {
        usn = headers.get("ST").getValue();
        // LogFactory.getLog(SSDPTests.class).debug("Search message " + usn);
        type = Type.SEARCH;
    } else if (Message.HTTP_OK_START.startsWith(command)) {
        // LogFactory.getLog(SSDPTests.class).debug("Response message");
        type = Type.RESPONSE;
    } else
        throw new RuntimeException("unknown type");
    return new Message(type, headers, usn, packet,
            new String(packet.getData(), 0, packet.getLength(), Charsets.US_ASCII));
}

From source file:Reflector.java

public void packetReceived(DatagramPacket packet) {
    // An incoming packet has been received. Override
    // the old packet addressing to the new outgoing
    // addressing, send it and log it.

    try {/*from  w w w.j  a v  a 2  s. co m*/
        packet.setAddress(sendAddr);
        packet.setPort(sendPort);
        ds.send(packet);
        logger.log("Packet forwarded to " + packet.getAddress().getHostAddress() + "/" + packet.getPort() + ", "
                + packet.getLength() + " bytes");
    } catch (IOException e) {
        System.err.println("Error sending packet");
        e.printStackTrace();
    }
}

From source file:org.lockss.test.LockssTestCase.java

/**
 * Asserts that the two DatagramPackets have equal contents
 * @param expected the expected value/*from   ww w.j av a2  s  . c  o  m*/
 * @param actual the actual value
 */
public static void assertEquals(DatagramPacket expected, DatagramPacket actual) {
    assertEquals(expected.getAddress(), actual.getAddress());
    assertEquals(expected.getPort(), actual.getPort());
    assertEquals(expected.getLength(), actual.getLength());
    assertEquals(expected.getOffset(), actual.getOffset());
    assertTrue(Arrays.equals(expected.getData(), actual.getData()));
}

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//from w w  w  . j  a  v a2 s  .  com
        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.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();/*from  w ww  .ja v  a 2  s  .c om*/
                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();
}

From source file:ws.argo.Responder.Responder.java

public void run() throws IOException, ClassNotFoundException {

    ArrayList<ProbeHandlerPluginIntf> handlers = new ArrayList<ProbeHandlerPluginIntf>();

    // load up the handler classes specified in the configuration parameters
    // I hope the hander classes are in a jar file on the classpath
    handlers = loadHandlerPlugins(cliValues.config.appHandlerConfigs);

    @SuppressWarnings("resource")
    MulticastSocket socket = new MulticastSocket(cliValues.config.multicastPort);
    address = InetAddress.getByName(cliValues.config.multicastAddress);
    LOGGER.info("Starting Responder on " + address.toString() + ":" + cliValues.config.multicastPort);
    socket.joinGroup(address);/*w  w  w . j a va 2  s .c o m*/

    DatagramPacket packet;
    ResponsePayloadBean response = null;

    LOGGER.info(
            "Responder started on " + cliValues.config.multicastAddress + ":" + cliValues.config.multicastPort);

    httpClient = HttpClients.createDefault();

    LOGGER.fine("Starting Responder loop - infinite until process terminated");
    // infinite loop until the responder is terminated
    while (true) {

        byte[] buf = new byte[1024];
        packet = new DatagramPacket(buf, buf.length);
        LOGGER.fine("Waiting to recieve packet...");
        socket.receive(packet);

        LOGGER.fine("Received packet");
        LOGGER.fine("Packet contents:");
        // Get the string
        String probeStr = new String(packet.getData(), 0, packet.getLength());
        LOGGER.fine("Probe: \n" + probeStr);

        try {
            ProbePayloadBean payload = parseProbePayload(probeStr);

            LOGGER.info("Received probe id: " + payload.probeID);

            // Only handle probes that we haven't handled before
            // The Probe Generator needs to send a stream of identical UDP packets
            // to compensate for UDP reliability issues.  Therefore, the Responder
            // will likely get more than 1 identical probe.  We should ignore duplicates.
            if (!handledProbes.contains(payload.probeID)) {
                for (ProbeHandlerPluginIntf handler : handlers) {
                    response = handler.probeEvent(payload);
                    sendResponse(payload.respondToURL, payload.respondToPayloadType, response);
                }
                handledProbes.add(payload.probeID);
            } else {
                LOGGER.info("Discarding duplicate probe with id: " + payload.probeID);
            }

        } catch (SAXException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        }

    }

}

From source file:org.restcomm.sbc.media.MediaZone.java

public void send(DatagramPacket dgram) throws IOException {

    if (dgram == null)
        return;/*from w  w w  . j a  v a2s  .c o  m*/

    dgram.setAddress(mediaZonePeer.getOriginalAddress());
    dgram.setPort(mediaZonePeer.getOriginalRtpPort());
    //dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength()), 0, dgram.getLength() );   
    //LOG.trace("--->("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]");   
    //LOG.trace("---> via socket "+toPrint(socket));   
    if (dgram.getData().length > 8) {
        if (logCounter == rtpCountLog) {
            RawPacket rtp = new RawPacket(dgram.getData(), 0, dgram.getLength());
            LOG.trace("--->[PayloadType " + rtp.getPayloadType() + "](" + this.mediaType + ", " + this.direction
                    + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":"
                    + dgram.getPort() + "[" + dgram.getLength() + "]");
            logCounter = 0;
        }
    } else {
        LOG.warn("--->[PayloadType ?](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost
                + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength()
                + "]");
    }

    packetsSentCounter++;

    socket.send(dgram);

}

From source file:org.jitsi.videobridge.VideoChannel.java

/**
 * {@inheritDoc}//from  www . jav a 2s  .co  m
 */
@Override
protected boolean acceptDataInputStreamDatagramPacket(DatagramPacket p) {
    boolean accept = super.acceptDataInputStreamDatagramPacket(p);

    if (accept) {
        // TODO: find a way to do this only in case it is actually needed
        // (currently this means when there is another channel in the
        // same content, with adaptive-last-n turned on), in order to not
        // waste resources.
        // XXX should we also count bytes received for RTCP towards the
        // incoming bitrate?
        incomingBitrate.update(p.getLength(), System.currentTimeMillis());
    }

    return accept;
}