Java Code Examples for java.net.DatagramPacket#getLength()

The following examples show how to use java.net.DatagramPacket#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IPMidiInput.java    From PdDroidPublisher with GNU General Public License v3.0 6 votes vote down vote up
private void recvMessage(DatagramPacket pack)
{
	byte [] buffer = pack.getData();
	int len = pack.getLength();
	byte [] data;
	if(len - 1 < NUM_BUFFERS)
	{
		data = buffers[len - 1];
	}
	else
	{
		data = new byte[len];
	}
	for(int i=0 ; i<len ;i++)
	{
		data[i] = buffer[i];
	}
	listener.onMidiMessage(data);

}
 
Example 2
Source File: PRUDPPacketHandlerSocks.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
public void
transformSend(
	DatagramPacket	packet )
{	
	if ( relay == null ){
		
		return;
	}
	
	byte[]	data 		= packet.getData();
	int		data_len	= packet.getLength();
	
	byte[]	new_data = new byte[data_len+packet_out_header.length];
	
	System.arraycopy( packet_out_header, 0, new_data, 0, packet_out_header.length );
	System.arraycopy( data, 0, new_data, packet_out_header.length, data_len);
	
	packet.setData( new_data );
}
 
Example 3
Source File: StatsDReporterTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	while (running) {
		try {
			byte[] buffer = new byte[1024];

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

			socket.receive(packet);

			String line = new String(packet.getData(), 0, packet.getLength(), ConfigConstants.DEFAULT_CHARSET);

			lines.put(line, obj);

			synchronized (lines) {
				lines.notifyAll();
			}
		} catch (IOException ex) {
			// ignore the exceptions
		}
	}
}
 
Example 4
Source File: SendSize.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        System.err.println("started server thread: " + server);
        byte[] buf = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(buf,
                                                          buf.length);
        server.receive(receivePacket);
        int len = receivePacket.getLength();
        switch(len) {
        case packetLength:
            System.out.println("receive length is: " + len);
            break;
        default:
            throw new RuntimeException(
                "receive length is: " + len +
                ", send length: " + packetLength +
                ", buffer length: " + buf.length);
        }
        return;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("caugth: " + e);
    } finally {
        if (server != null) { server.close(); }
    }
}
 
Example 5
Source File: SendSize.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        System.err.println("started server thread: " + server);
        byte[] buf = new byte[1024];
        DatagramPacket receivePacket = new DatagramPacket(buf,
                                                          buf.length);
        server.receive(receivePacket);
        int len = receivePacket.getLength();
        switch(len) {
        case packetLength:
            System.out.println("receive length is: " + len);
            break;
        default:
            throw new RuntimeException(
                "receive length is: " + len +
                ", send length: " + packetLength +
                ", buffer length: " + buf.length);
        }
        return;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("caugth: " + e);
    } finally {
        if (server != null) { server.close(); }
    }
}
 
Example 6
Source File: Two.java    From JavaBase with MIT License 6 votes vote down vote up
public static void main(String[] args) {
  try {
    InetAddress group = InetAddress.getByName(address);
    MulticastSocket multicastSocket = new MulticastSocket(port);
    multicastSocket.joinGroup(group);
    byte[] buffer = new byte[1024];

    while (true) {
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      multicastSocket.receive(packet);

      String str = new String(packet.getData(), 0, packet.getLength());
      log.info("str={}", str);
    }
  } catch (Exception e) {
    log.error("", e);
  }
}
 
Example 7
Source File: UDPSoulissDecoder.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get packet from VNET Frame
 * 
 * @param packet
 *            incoming datagram
 */
public void decodeVNetDatagram(DatagramPacket packet) {
	int checklen = packet.getLength();
	ArrayList<Short> mac = new ArrayList<Short>();
	for (int ig = 7; ig < checklen; ig++) {
		mac.add((short) (packet.getData()[ig] & 0xFF));
	}
	decodeMacaco(mac);
}
 
Example 8
Source File: UdpReceiverActivity.java    From AndroidDemo with MIT License 5 votes vote down vote up
@Override
public void run() {
    if (receiverSocket != null) {
        while (true) {
            if (interrupted()) break;
            try {
                DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
                receiverSocket.receive(packet);
                final String data = new String(packet.getData(), 0, packet.getLength());
                if (data.length() > 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            text.append("\r\n");
                            text.append(data);
                            scrollView.fullScroll(View.FOCUS_DOWN);

                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }
    }
}
 
Example 9
Source File: UdpReceiver.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
public static void main(String[] args){
    try(DatagramSocket ds = new DatagramSocket(3333)){
        DatagramPacket dp = new DatagramPacket(new byte[30], 30);
        ds.receive(dp);
        int i = 1;
        for(byte b: dp.getData()){
            System.out.print(Character.toString(b));
            if(i++ == dp.getLength()){
                break;
            }
        }
    } catch (Exception ex){
        ex.printStackTrace();
    }
}
 
Example 10
Source File: TestPutUDP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private byte[] getPacketData(final DatagramPacket packet) {
    final int length = packet.getLength();
    final byte[] packetData = packet.getData();
    final byte[] resizedPacketData = new byte[length];
    for (int i = 0; i < length; i++) {
        resizedPacketData[i] = packetData[i];
    }
    return resizedPacketData;
}
 
Example 11
Source File: UdpMulticastDataSource.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
@Override
public int read(byte[] buffer, int offset, int readLength) throws IOException {

    if( !opened )
        return 0;

    DatagramPacket packet = new DatagramPacket(buffer, offset, readLength);
    socket.receive(packet);

    return packet.getLength();
}
 
Example 12
Source File: UdpUnicastDataSource.java    From Exoplayer_VLC with Apache License 2.0 5 votes vote down vote up
@Override
public int read(byte[] buffer, int offset, int readLength) throws IOException {
    if (readLength > rcvBufferSize) {
        rcvBufferSize = readLength+1;
        socket.setReceiveBufferSize(rcvBufferSize);
    }
    DatagramPacket packet = new DatagramPacket(buffer, offset, readLength);
    socket.receive(packet);
    Log.i(TAG, ">>>> read "+packet.getLength() + " MMMMMMMMMMM " + readLength);
    Util.printByteArray(TAG, packet.getData(), offset, 50);
    Util.findThisByte("sync interval ", (byte) 0x47, packet.getData());
    return packet.getLength();
}
 
Example 13
Source File: DatagramMatcher.java    From sr201 with MIT License 5 votes vote down vote up
@Override
public boolean matches(final Object argument) {
	final DatagramPacket p = (DatagramPacket) argument;
	return //
	// compare IP addresses
	p.getAddress().equals(ipAdr) //
			// compare ports
			&& p.getPort() == port //
			// and data length
			&& p.getLength() == data.length() //
			// compare data
			&& data.equals(new String(p.getData(), StandardCharsets.US_ASCII));
}
 
Example 14
Source File: MixerStatus.java    From beat-link with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor sets all the immutable interpreted fields based on the packet content.
 *
 * @param packet the beat announcement packet that was received
 */
@SuppressWarnings("WeakerAccess")
public MixerStatus(DatagramPacket packet) {
    super(packet, "Mixer update", packet.getLength());

    if (packetBytes.length < MINIMUM_PACKET_SIZE) {
        throw new IllegalArgumentException("Unable to create a MixerStatus object, packet too short: we need " + MINIMUM_PACKET_SIZE +
                " bytes and were given only " + packetBytes.length);
    }

    final int payloadLength = (int)Util.bytesToNumber(packetBytes, 0x22, 2);
    final byte subtype = packetBytes[0x20];
    switch (subtype) {
        case 0:  // Actual mixer status packets use this subtype
            if (packetBytes.length != payloadLength + 0x24) {
                logger.warn("Received Mixer status packet with reported payload length of " + payloadLength + " and actual payload length of " +
                        (packetBytes.length - 0x24) + ": " + this);
            }
            break;

        case 1:  // rekordbox seems to sometimes send packets with this subtype
            if (packetBytes.length != payloadLength) {
                logger.warn("Received Mixer status packet with reported length of " + payloadLength + " and actual length of " +
                        (packetBytes.length) + ": " + this);
            }
            break;

        default:
            logger.warn("Received Mixer status packet with unexpected subtype " + subtype + ": " + this);
    }

    if (!expectedStatusPacketSizes.contains(packetBytes.length)) {
        logger.warn("Processing Mixer Status packets with unexpected lengths " + packetBytes.length + ".");
        expectedStatusPacketSizes.add(packetBytes.length);
    }

    pitch = (int)Util.bytesToNumber(packetBytes, 0x28, 4);
    bpm = (int)Util.bytesToNumber(packetBytes, 0x2e, 2);
    handingMasterToDevice = Util.unsign(packetBytes[MASTER_HAND_OFF]);
}
 
Example 15
Source File: UDPSyslogServer.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void run() {
    this.shutdown = false;
    try {
        this.ds = createDatagramSocket();
    } catch (Exception e) {
        LOGGER.error("Creating DatagramSocket failed", e);
        throw new SyslogRuntimeException(e);
    }

    byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];

    while (!this.shutdown) {
        try {
            final DatagramPacket dp = new DatagramPacket(receiveData, receiveData.length);
            this.ds.receive(dp);
            final SyslogServerEventIF event = new Rfc5424SyslogEvent(receiveData, dp.getOffset(), dp.getLength());
            List list = this.syslogServerConfig.getEventHandlers();
            for (int i = 0; i < list.size(); i++) {
                SyslogServerEventHandlerIF eventHandler = (SyslogServerEventHandlerIF) list.get(i);
                eventHandler.event(this, event);
            }
        } catch (SocketException se) {
            LOGGER.warn("SocketException occurred", se);
        } catch (IOException ioe) {
            LOGGER.warn("IOException occurred", ioe);
        }
    }
}
 
Example 16
Source File: TestGangliaMetrics.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void send(DatagramPacket p) throws IOException {
  // capture the byte arrays
  byte[] bytes = new byte[p.getLength()];
  System.arraycopy(p.getData(), p.getOffset(), bytes, 0, p.getLength());
  capture.add(bytes);
}
 
Example 17
Source File: SnmpResponseHandler.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
public synchronized void processDatagram(DatagramPacket dgrm) {

        byte []data = dgrm.getData();
        int datalen = dgrm.getLength();

        if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
            SNMP_ADAPTOR_LOGGER.logp(Level.FINER, SnmpResponseHandler.class.getName(),
                "action", "processDatagram", "Received from " + dgrm.getAddress().toString() +
                 " Length = " + datalen + "\nDump : \n" + SnmpMessage.dumpHexBuffer(data, 0, datalen));
        }

        try {
            SnmpMessage msg = new SnmpMessage();
            msg.decodeMessage(data, datalen);
            msg.address = dgrm.getAddress();
            msg.port = dgrm.getPort();

            // Retreive the PDU factory of the SNMP adaptor to decode the received inform response.
            //
            SnmpPduFactory pduFactory = adaptor.getPduFactory();
            if (pduFactory == null) {
                if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
                    SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(),
                        "processDatagram", "Dropping packet. Unable to find the pdu factory of the SNMP adaptor server");
                }
            }
            else {
                SnmpPduPacket snmpProt = (SnmpPduPacket)pduFactory.decodeSnmpPdu(msg);

                if (snmpProt == null) {
                    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
                        SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(),
                            "processDatagram", "Dropping packet. Pdu factory returned a null value");
                    }
                }
                else if (snmpProt instanceof SnmpPduRequest) {

                    SnmpPduRequest pduReq = (SnmpPduRequest)snmpProt;
                    SnmpInformRequest req = snmpq.removeRequest(pduReq.requestId) ;
                    if (req != null) {
                        req.invokeOnResponse(pduReq);
                    } else {
                        if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
                            SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(),
                                "processDatagram", "Dropping packet. Unable to find corresponding for InformRequestId = " + pduReq.requestId);
                        }
                    }
                }
                else {
                    if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
                        SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(),
                            "processDatagram", "Dropping packet. The packet does not contain an inform response");
                    }
                }
                snmpProt = null ;
            }
        } catch (Exception e) {
            if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINEST)) {
                SNMP_ADAPTOR_LOGGER.logp(Level.FINEST, SnmpResponseHandler.class.getName(),
                    "processDatagram", "Exception while processsing", e);
            }
        }
    }
 
Example 18
Source File: UdpSingleClientServer.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
@Override
public Integer call() {
	isRunning.set(true);

	Set<Integer> packetReceived = new TreeSet<>();
	
	try {
		while (isRunning.get()) {
			byte[] buffer = new byte[BUFFER_LENGTH];
			DatagramPacket dp = new DatagramPacket(buffer, BUFFER_LENGTH);
			
			socket.receive(dp);
			receivedPackets++;
			byte[] data = dp.getData();
			
			//check udp packet:
			if (data[0] != UDP_IN_TEST_IDENTIFIER) {
				throw new IOException("bad UDP IN TEST identifier");
			}

			//check for duplicate packets:
			int packetNumber = data[1];
			if (packetReceived.contains(packetNumber)) {
				throw new IOException("duplicate UDP IN TEST packet");
			}
			
			
			char[] uuid = new char[dp.getLength() - 2];
			for (int i = 2; i < dp.getLength(); i++) {
				uuid[i-2] = (char) data[i];
			}
			
			if (TestServer.serverPreferences.getVerboseLevel() >= 1) {
				TestServerConsole.log("received UDP from: " + dp.getAddress().toString() + ", #" + packetNumber + ", uuid: " + String.valueOf(uuid), 1, TestServerServiceEnum.UDP_SERVICE);
			}

			//received enough packets? exit loop
			if (receivedPackets >= numPackets) {
				break;
			}
		}		
	} 
	catch (Exception e) {
		e.printStackTrace();
	}
	finally {
		if (!socket.isClosed()) {
			socket.close();
		}
	}
	
	TestServerConsole.log("UdpServer shutdown on port: " + socket.getPort(), 0, TestServerServiceEnum.UDP_SERVICE);
	return new Integer(receivedPackets);
}
 
Example 19
Source File: UdpMessageWorker.java    From bt with Apache License 2.0 4 votes vote down vote up
private <T> T doSend(UdpTrackerMessage message, Session session, UdpTrackerResponseHandler<T> responseHandler) {
    DatagramSocket socket = getSocket();
    try {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("[Session {}] Sending message {} to remote address: {}",
                    session.getId(), message, remoteAddress);
        }
        socket.send(serialize(message, session));
        DatagramPacket response = new DatagramPacket(new byte[8192], 8192);

        while (true) {
            socket.receive(response);

            if (!remoteAddress.equals(response.getSocketAddress())) {
                // ignore packets received from unexpected senders
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("[Session {}] Received unexpected datagram packet from remote address: {}",
                            session.getId(), response.getSocketAddress());
                }
                continue;
            }

            if (response.getLength() >= MIN_MESSAGE_LENGTH) {
                byte[] data = response.getData();

                int messageType = Protocols.readInt(data, MESSAGE_TYPE_OFFSET);
                if (messageType == ERROR_MESSAGE_TYPE) {
                    String error = new String(Arrays.copyOfRange(data, DATA_OFFSET, response.getLength()), StandardCharsets.US_ASCII);
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("[Session {}] Received error from remote address: {}; " +
                                "message ID: {}, messageType: {}, error: {}",
                                session.getId(), remoteAddress, message.getId(), messageType, error);
                    }
                    return responseHandler.onError(error);
                } else if (messageType != message.getMessageType()) {
                    // ignore messages with incorrect type
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("[Session {}] Received message with incorrect type " +
                                "from remote address: {}; expected: {}, actual: {}",
                                session.getId(), remoteAddress, message.getMessageType(), messageType);
                    }
                    continue;
                }

                int messageId = Protocols.readInt(data, MESSAGE_ID_OFFSET);
                if (messageId != message.getId()) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("[Session {}] Received message with incorrect message ID " +
                                "from remote address: {}; expected: {}, actual: {}",
                                session.getId(), remoteAddress, message.getId(), messageId);
                    }
                    continue;
                }

                T result = responseHandler.onSuccess(Arrays.copyOfRange(data, DATA_OFFSET, response.getLength()));
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("[Session {}] Received response " +
                            "from remote address: {}; message ID: {}, messageType: {}, result: {}",
                            session.getId(), remoteAddress, messageId, messageType, result);
                }
                return result;

            } else if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("[Session {}] Received message with incorrect size " +
                        "from remote address: {}; expected: at least {} bytes, actual: {} bytes",
                        session.getId(), remoteAddress, MIN_MESSAGE_LENGTH, response.getLength());
            }
        }
    } catch (IOException e) {
        throw new BtException("Interaction with the tracker failed {remoteAddress=" + remoteAddress + "}", e);
    }
}
 
Example 20
Source File: UdpSource.java    From Azzet with Open Software License 3.0 2 votes vote down vote up
/**
 * Parses the request from the given DatagramPacket.
 * 
 * @param packet
 *        The packet to parse the request from.
 * @return The request contained in the packet.
 */
public static String getRequest( DatagramPacket packet )
{
	return new String( packet.getData(), 0, packet.getLength() );
}