Example usage for java.net DatagramPacket getData

List of usage examples for java.net DatagramPacket getData

Introduction

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

Prototype

public synchronized byte[] getData() 

Source Link

Document

Returns the data buffer.

Usage

From source file:org.squidy.manager.protocol.multicast.MulticastServer.java

@Override
public void run() {
    while (running) {
        try {/*  w w  w.  j a  v a 2 s . c  o  m*/
            byte[] buffer = new byte[BUFFER_SIZE];
            DatagramPacket packet = new DatagramPacket(buffer, BUFFER_SIZE);
            socket.receive(packet);
            data = new String(packet.getData());
            int last = 0;
            while (last < BUFFER_SIZE) {
                if (buffer[last] == 0)
                    break;
                last++;
            }
            data = data.substring(0, last);
            if (last == BUFFER_SIZE) {
                LOG.error("Input buffer overflow");
            } else {
                for (MulticastListener listener : listeners) {
                    listener.parseData(data);
                }
            }

            for (MulticastListener listener : listeners) {
                listener.parseData(packet.getData());
            }
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Connection error occured.");
            }
        }
    }
    socket.close();
}

From source file:org.libreoffice.impressremote.communication.TcpServersFinder.java

private String receiveSearchResult(DatagramPacket aSearchResultPacket) {
    try {/*w  ww . j a  va 2s  .com*/
        mSearchSocket.receive(aSearchResultPacket);

        return new String(aSearchResultPacket.getData(), Protocol.CHARSET);
    } catch (SocketTimeoutException e) {
        return "";
    } catch (IOException e) {
        return "";
    }
}

From source file:org.nuxeo.runtime.detection.MulticastDetector.java

private String readHeartBeat(DatagramPacket p) {
    return new String(p.getData(), p.getOffset(), p.getLength());
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPAckPacket.java

/***
 * Creates an acknowledgement packet based from a received
 * datagram.  Assumes the datagram is at least length 4, else an
 * ArrayIndexOutOfBoundsException may be thrown.
 * <p>/*from   www  .  j  av  a  2s  .c om*/
 * @param datagram  The datagram containing the received acknowledgement.
 * @throws TFTPPacketException  If the datagram isn't a valid TFTP
 *         acknowledgement packet.
 ***/
TFTPAckPacket(DatagramPacket datagram) throws TFTPPacketException {
    super(TFTPPacket.ACKNOWLEDGEMENT, datagram.getAddress(), datagram.getPort());
    byte[] data;

    data = datagram.getData();

    if (getType() != data[1])
        throw new TFTPPacketException("TFTP operator code does not match type.");

    _blockNumber = (((data[2] & 0xff) << 8) | (data[3] & 0xff));
}

From source file:org.graylog2.messagehandlers.gelf.GELFTest.java

/**
 * Test getGELFType method with an invalid encryption
 *///from   w  w w.  j a  v a 2 s .  c  o  m
@Test(expected = InvalidGELFCompressionMethodException.class)
public void testGetGELFTypeWithInvalidEncryption() throws Exception {
    // Build a datagram packet.
    String invalidlyEncryptedString = "mamamamamamamamamamamama";
    DatagramPacket invalidGELFMessage = new DatagramPacket(invalidlyEncryptedString.getBytes(),
            invalidlyEncryptedString.getBytes().length);

    // Cause the exception we expect.
    GELF.getGELFType(invalidGELFMessage.getData());
}

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

@Override
public void run() {
    DatagramSocket sock = null;/*w  w w. java 2  s  . 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:org.dragonet.net.inf.mcpe.NetworkHandler.java

private void processPacket(DatagramPacket packet) {
    try {/*  www.j  av  a2  s  .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:gravity.android.discovery.DiscoveryServer.java

public void run() {
    Log.v("DISCOVERY_SERVER", "SERVER STARTED");

    DatagramSocket serverSocket = null;

    try {//from   w w  w . j a  v  a  2 s  .  co  m
        serverSocket = new DatagramSocket(port);
        byte[] receiveData;
        byte[] sendData;

        while (this.isInterrupted() == false) {
            receiveData = new byte[128];
            sendData = new byte[128];

            try {
                Log.v("DISCOVERY_SERVER", "LISTENING");
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());

                if (sentence != null)
                    Log.v("DISCOVERY_SERVER",
                            "RECEIVED: " + sentence.substring(0, receivePacket.getLength()).trim());

                if (sentence != null && sentence.substring(0, receivePacket.getLength()).trim().equals(token)) {
                    Log.v("DISCOVERY_SERVER", "SEND '" + nome + "' to "
                            + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort());
                    JSONObject sendDataJson = new JSONObject();
                    sendDataJson.accumulate("name", nome);
                    sendDataJson.accumulate("port_to_share", port_to_share);

                    //sendData = (nome + "," + port_to_share).getBytes();
                    sendData = sendDataJson.toString().getBytes(); //Prakash: converts the data to json objects to avoid troubles

                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                            receivePacket.getAddress(), receivePacket.getPort());
                    serverSocket.send(sendPacket);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("DISCOVERY_SERVER", ex.toString());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("DISCOVERY_SERVER", e.toString());
    } finally {
        try {
            if (serverSocket != null)
                serverSocket.close();
        } catch (Exception ex) {
        }
    }

}

From source file:org.hyperic.util.ntp.NtpClient.java

public NtpResponse getResponse() throws SocketException, UnknownHostException, IOException {
    DatagramSocket socket = new DatagramSocket();
    socket.setSoTimeout(this.timeout);

    InetAddress address = InetAddress.getByName(this.hostname);
    byte[] data = NtpResponse.getRequestBytes();
    DatagramPacket packet = new DatagramPacket(data, data.length, address, this.port);
    socket.send(packet);/*w w  w  .  j ava2 s .c o m*/

    packet = new DatagramPacket(data, data.length);
    socket.receive(packet);

    NtpResponse response = NtpResponse.decodeResponse(now(), packet.getData());
    return response;
}

From source file:fi.tut.fast.MulticastConsumer.java

private void consume() throws IOException {
    byte buf[] = new byte[endpoint.getMaxPacketSize()];
    DatagramPacket pack = new DatagramPacket(buf, buf.length);
    try {/*from  w  w w. ja  va2s.c  o m*/
        s.receive(pack);
        try {
            messageQueue.add(new ExchangeDeliveryJob(pack.getData(), pack.getLength()));
        } catch (Exception e) {
            LOG.error("Exception Caught while processing UDP message.", e);
        }
    } catch (java.net.SocketTimeoutException ex) {
        // Timed out.. Listen again.
    }
}