List of usage examples for java.net DatagramPacket getLength
public synchronized int getLength()
From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java
@SuppressWarnings("unchecked") @Test/*from ww w .j av a 2 s .c om*/ public void testUnicastReceiverWithReply() throws Exception { QueueChannel channel = new QueueChannel(2); int port = SocketUtils.findAvailableUdpSocket(); UnicastReceivingChannelAdapter adapter = new UnicastReceivingChannelAdapter(port); adapter.setOutputChannel(channel); adapter.start(); SocketTestUtils.waitListening(adapter); Message<byte[]> message = MessageBuilder.withPayload("ABCD".getBytes()).build(); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress("localhost", port)); final DatagramSocket socket = new DatagramSocket(SocketUtils.findAvailableUdpSocket()); socket.send(packet); final AtomicReference<DatagramPacket> theAnswer = new AtomicReference<DatagramPacket>(); final CountDownLatch receiverReadyLatch = new CountDownLatch(1); final CountDownLatch replyReceivedLatch = new CountDownLatch(1); //main thread sends the reply using the headers, this thread will receive it Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { DatagramPacket answer = new DatagramPacket(new byte[2000], 2000); try { receiverReadyLatch.countDown(); socket.receive(answer); theAnswer.set(answer); replyReceivedLatch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }); Message<byte[]> receivedMessage = (Message<byte[]>) channel.receive(2000); assertEquals(new String(message.getPayload()), new String(receivedMessage.getPayload())); String replyString = "reply:" + System.currentTimeMillis(); byte[] replyBytes = replyString.getBytes(); DatagramPacket reply = new DatagramPacket(replyBytes, replyBytes.length); reply.setSocketAddress( new InetSocketAddress((String) receivedMessage.getHeaders().get(IpHeaders.IP_ADDRESS), (Integer) receivedMessage.getHeaders().get(IpHeaders.PORT))); assertTrue(receiverReadyLatch.await(10, TimeUnit.SECONDS)); new DatagramSocket().send(reply); assertTrue(replyReceivedLatch.await(10, TimeUnit.SECONDS)); DatagramPacket answerPacket = theAnswer.get(); assertNotNull(answerPacket); assertEquals(replyString, new String(answerPacket.getData(), 0, answerPacket.getLength())); }
From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java
@Test() @Ignore("Can only be executed if an Asterix sender is feeding the decoder") public void when_upd_unicast_is_used_as_input_should_decode_cat062_messages_from_larger_sample() throws IOException { //arrange/*from w w w . ja v a2 s. co m*/ final int PORT = 3002; final int MAX_PACKET_SIZE = 65507; final int TIMEOUT = 5000; //act AsterixDecoder decoder = new AsterixDecoder(62, 65); byte[] networkBuffer = new byte[MAX_PACKET_SIZE]; int receivedDatagrams = 0; int receivedBytes = 0; try (DatagramSocket client = new DatagramSocket(PORT)) { client.setSoTimeout(TIMEOUT); DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length); while (true) { client.receive(packet); decoder.decode(networkBuffer, 0, packet.getLength()); //accumulate and print info receivedDatagrams++; receivedBytes += packet.getLength(); if (receivedDatagrams % 100 == 0) { System.out .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes"); } } } catch (IOException e) { System.out.println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes"); } //assert int expectedDatagrams = 18163; int expectedBytes = 2785805; assertEquals(expectedDatagrams, receivedDatagrams); assertEquals(expectedBytes, receivedBytes); }
From source file:com.offbynull.portmapper.natpmp.NatPmpReceiver.java
/** * Start listening for NAT-PMP events. This method blocks until {@link #stop() } is called. * @param listener listener to notify of events * @throws IOException if socket error occurs * @throws NullPointerException if any argument is {@code null} *///from www . jav a 2 s . com public void start(NatPmpEventListener listener) throws IOException { Validate.notNull(listener); MulticastSocket socket = null; try { final InetAddress group = InetAddress.getByName("224.0.0.1"); // NOPMD final int port = 5350; final InetSocketAddress groupAddress = new InetSocketAddress(group, port); socket = new MulticastSocket(port); if (!currentSocket.compareAndSet(null, socket)) { IOUtils.closeQuietly(socket); return; } socket.setReuseAddress(true); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); Enumeration<InetAddress> addrs = networkInterface.getInetAddresses(); while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface InetAddress addr = addrs.nextElement(); try { if (addr instanceof Inet4Address) { socket.joinGroup(groupAddress, networkInterface); } } catch (IOException ioe) { // NOPMD // occurs with certain interfaces // do nothing } } } ByteBuffer buffer = ByteBuffer.allocate(12); DatagramPacket data = new DatagramPacket(buffer.array(), buffer.capacity()); while (true) { buffer.clear(); socket.receive(data); buffer.position(data.getLength()); buffer.flip(); if (!data.getAddress().equals(gatewayAddress)) { // data isn't from our gateway, ignore continue; } if (buffer.remaining() != 12) { // data isn't the expected size, ignore continue; } int version = buffer.get(0); if (version != 0) { // data doesn't have the correct version, ignore continue; } int opcode = buffer.get(1) & 0xFF; if (opcode != 128) { // data doesn't have the correct op, ignore continue; } int resultCode = buffer.getShort(2) & 0xFFFF; switch (resultCode) { case 0: break; default: continue; // data doesn't have a successful result, ignore } listener.publicAddressUpdated(new ExternalAddressNatPmpResponse(buffer)); } } catch (IOException ioe) { if (currentSocket.get() == null) { return; // ioexception caused by interruption/stop, so just return without propogating error up } throw ioe; } finally { IOUtils.closeQuietly(socket); currentSocket.set(null); } }
From source file:jlg.jade.test.asterix.cat062.Cat062LargeSampleTest.java
@Test @Ignore("Can only be executed if an Asterix sender is feeding the decoder") public void when_upd_unicast_is_used_as_input_and_datagram_is_large_should_decode_cat062_messages_from_larger_sample() throws IOException { //arrange/*from w w w. j a v a2 s .c o m*/ final int PORT = 3001; final int MAX_PACKET_SIZE = 65507; final int TIMEOUT = 20000; //act AsterixDecoder decoder = new AsterixDecoder(62); byte[] networkBuffer = new byte[MAX_PACKET_SIZE]; int receivedDatagrams = 0; int receivedBytes = 0; try (DatagramSocket client = new DatagramSocket(PORT)) { client.setSoTimeout(TIMEOUT); DatagramPacket packet = new DatagramPacket(networkBuffer, networkBuffer.length); while (true) { client.receive(packet); List<AsterixDataBlock> dataBlocks = decoder.decode(networkBuffer, 0, packet.getLength()); for (AsterixDataBlock dataBlock : dataBlocks) { for (AsterixRecord rec : dataBlock.getRecords()) { System.out.println("Decoded new record"); } } //accumulate and print info receivedDatagrams++; receivedBytes += packet.getLength(); if (receivedDatagrams % 100 == 0) { System.out .println("Processed " + receivedDatagrams + " datagrams (" + receivedBytes + ") bytes"); } } } //assert //int expectedDatagrams = 34957; //int expectedBytes = 2306154; //assertEquals(expectedDatagrams, receivedDatagrams); //assertEquals(expectedBytes, receivedBytes); }
From source file:com.springrts.springls.nat.NatHelpServer.java
/** * check UDP server for any new packets/* w ww .j av a 2 s . c om*/ */ private void checkForNewPackets() { DatagramPacket packet; while ((packet = fetchNextPackage()) != null) { InetAddress address = packet.getAddress(); int clientPort = packet.getPort(); String data = new String(packet.getData(), packet.getOffset(), packet.getLength()); LOG.trace("*** UDP packet received from {} from port {}", address.getHostAddress(), clientPort); Client client = getContext().getClients().getClient(data); if (client == null) { continue; } client.setUdpSourcePort(clientPort); client.sendLine(String.format("UDPSOURCEPORT %d", clientPort)); } }
From source file:org.lwes.emitter.UnicastEventEmitter.java
/** * @param bytes the byte array to emit// w ww. j a v a2 s. c om * @param address the address to use * @param port the port to use * @throws IOException throws an IOException if there is a network error */ protected void emit(byte[] bytes, InetAddress address, int port) throws IOException { /* don't send null bytes */ if (bytes == null) return; DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port); socket.send(dp); if (log.isTraceEnabled()) { log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength())); } }
From source file:org.eredlab.g4.ccl.net.tftp.TFTPErrorPacket.java
/*** * Creates an error packet based from a received * datagram. Assumes the datagram is at least length 4, else an * ArrayIndexOutOfBoundsException may be thrown. * <p>/*from w ww .ja va2 s. c om*/ * @param datagram The datagram containing the received error. * @throws TFTPPacketException If the datagram isn't a valid TFTP * error packet. ***/ TFTPErrorPacket(DatagramPacket datagram) throws TFTPPacketException { super(TFTPPacket.ERROR, datagram.getAddress(), datagram.getPort()); int index, length; byte[] data; StringBuffer buffer; data = datagram.getData(); length = datagram.getLength(); if (getType() != data[1]) throw new TFTPPacketException("TFTP operator code does not match type."); _error = (((data[2] & 0xff) << 8) | (data[3] & 0xff)); if (length < 5) throw new TFTPPacketException("Bad error packet. No message."); index = 4; buffer = new StringBuffer(); while (index < length && data[index] != 0) { buffer.append((char) data[index]); ++index; } _message = buffer.toString(); }
From source file:org.lwes.emitter.DatagramSocketEventEmitter.java
/** * @param bytes the byte array to emit//w ww .j a v a 2 s .c o m * @param address the address to use * @param port the port to use * @throws IOException throws an IOException if there is a network error * @return number of bytes emitted */ protected int emit(byte[] bytes, InetAddress address, int port) throws IOException { /* don't send null bytes */ if (bytes == null) return 0; if (socket == null || socket.isClosed()) { throw new IOException("Socket wasn't initialized or was closed."); } DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port); socket.send(dp); if (log.isTraceEnabled()) { log.trace("Sent to network '" + NumberCodec.byteArrayToHexString(dp.getData(), 0, dp.getLength())); } return bytes.length; }
From source file:com.byteatebit.nbserver.simple.TestSimpleNbServer.java
@Test public void testUdpEchoServer() throws IOException { SimpleNbServer simpleNbServer = SimpleNbServer.Builder.builder() .withConfig(/*from ww w .j a v a 2 s . c o m*/ SimpleNbServerConfig.builder().withListenAddress("localhost").withListenPort(1111).build()) .withConnectorFactory(UdpConnectorFactory.Builder.builder() .withDatagramMessageHandlerFactory(new UdpServiceFactory()).build()) .build(); simpleNbServer.start(); String message1 = "this is message1"; String message2 = "this is message2"; String message3 = "quit"; try { DatagramSocket socket = new DatagramSocket(); SocketAddress address = new InetSocketAddress("localhost", 1111); // message 1 byte[] payload1 = message1.getBytes(StandardCharsets.UTF_8); DatagramPacket packet = new DatagramPacket(payload1, payload1.length, address); socket.send(packet); byte[] response = new byte[50]; DatagramPacket responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); String messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message1, messageRead); // message2 byte[] payload2 = message2.getBytes(StandardCharsets.UTF_8); DatagramPacket packet2 = new DatagramPacket(payload2, payload2.length, address); socket.send(packet2); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals(message2, messageRead); // message3 byte[] payload3 = message3.getBytes(StandardCharsets.UTF_8); DatagramPacket packet3 = new DatagramPacket(payload3, payload3.length, address); socket.send(packet3); responsePacket = new DatagramPacket(response, response.length); socket.receive(responsePacket); messageRead = new String(responsePacket.getData(), 0, responsePacket.getLength()); Assert.assertEquals("goodbye", messageRead); } finally { simpleNbServer.shutdown(); } }
From source file:org.apache.axis2.transport.udp.UDPSender.java
private void waitForReply(MessageContext messageContext, DatagramSocket datagramSocket, String contentType) throws IOException { // piggy back message constant is used to pass a piggy back // message context in asnych model if (!(messageContext.getAxisOperation() instanceof OutInAxisOperation) && messageContext.getProperty(org.apache.axis2.Constants.PIGGYBACK_MESSAGE) == null) { return;// w ww.j av a 2 s . co m } byte[] inputBuffer = new byte[4096]; //TODO set the maximum size parameter DatagramPacket packet = new DatagramPacket(inputBuffer, inputBuffer.length); datagramSocket.receive(packet); // create the soap envelope try { MessageContext respMessageContext = messageContext.getOperationContext() .getMessageContext(WSDL2Constants.MESSAGE_LABEL_IN); InputStream inputStream = new ByteArrayInputStream(inputBuffer, 0, packet.getLength()); SOAPEnvelope envelope = TransportUtils.createSOAPMessage(respMessageContext, inputStream, contentType); respMessageContext.setEnvelope(envelope); } catch (XMLStreamException e) { throw new AxisFault("Can not build the soap message ", e); } }