List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:org.graylog2.messagehandlers.gelf.GELFTest.java
/** * Test of extractData method, of class GELF. *///from w ww . j a v a 2 s . c o m @Test public void testExtractData() throws Exception { // A GELF chunk header. Sequence 2 of 7. String header = "1e0fdf0fcb728fd5b73b0232"; String foo = asHex("foo".getBytes()); header = header + foo; byte[] headerHex = Hex.decodeHex(header.toCharArray()); DatagramPacket msg = new DatagramPacket(headerHex, headerHex.length); assertEquals("foo", new String(GELF.extractData(msg))); }
From source file:examples.ntp.SimpleNTPServer.java
/** * main thread to service client connections. */// w ww.ja va 2 s . c o m @Override public void run() { running = true; byte buffer[] = new byte[48]; final DatagramPacket request = new DatagramPacket(buffer, buffer.length); do { try { socket.receive(request); final long rcvTime = System.currentTimeMillis(); handlePacket(request, rcvTime); } catch (IOException e) { if (running) { e.printStackTrace(); } // otherwise socket thrown exception during shutdown } } while (running); }
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. j a v a 2s.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. } }
From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java
/** * Scans all messages that arrive on the socket and scans them for the * search keywords. The search is not case sensitive. * /* w ww . j a v a2s . c o m*/ * @param socket * The socket where the answers arrive. * @param keywords * The keywords to be searched for. * @return * @throws IOException */ private String scanResposesForKeywords(MulticastSocket socket, String... keywords) throws IOException { // In the worst case a SocketTimeoutException raises socket.setSoTimeout(2000); do { logger.debug("Got an answer message."); byte[] rxbuf = new byte[8192]; DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length); socket.receive(packet); String foundIp = analyzePacket(packet, keywords); if (foundIp != null) { return foundIp; } } while (true); }
From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSender.java
public boolean isNetworkAvailable() { final NetworkAvailabilityCheckPacket dto = new NetworkAvailabilityCheckPacket(); try {/*from w w w . j a v a 2 s . co m*/ final byte[] interBufferData = serialize(serializer, dto); final int interBufferSize = serializer.getInterBufferSize(); reusePacket.setData(interBufferData, 0, interBufferSize); udpSocket.send(reusePacket); if (logger.isInfoEnabled()) { logger.info("Data sent. {}", dto); } final byte[] receiveData = new byte[NetworkAvailabilityCheckPacket.DATA_OK.length]; final DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); udpSocket.receive(receivePacket); if (logger.isInfoEnabled()) { logger.info("Data received. {}", Arrays.toString(receivePacket.getData())); } return Arrays.equals(NetworkAvailabilityCheckPacket.DATA_OK, receiveData); } catch (IOException e) { logger.warn("packet send error {}", dto, e); return false; } }
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 w ww.j a v a 2 s. c om 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:org.libreoffice.impressremote.communication.TcpServersFinder.java
private DatagramPacket buildSearchResultPacket() { byte[] aSearchResultBuffer = new byte[SEARCH_RESULT_BUFFER_SIZE]; return new DatagramPacket(aSearchResultBuffer, aSearchResultBuffer.length); }
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;/*ww w . j a va 2 s .c om*/ } 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); } }
From source file:com.springrts.springls.nat.NatHelpServer.java
@Override public void run() { Configuration conf = getContext().getService(Configuration.class); int port = conf.getInt(ServerConfiguration.NAT_PORT); try {/*w ww.j a v a2s. c om*/ socket = new DatagramSocket(port); } catch (Exception ex) { LOG.warn("Unable to start UDP server on port " + port + ". Ignoring ...", ex); return; } LOG.info("Listening for connections on UDP port {} ...", port); byte[] buffer = new byte[RECEIVE_BUFFER_SIZE]; while (true) { try { if (myThread.isInterrupted()) { break; } // receive packet DatagramPacket packet = new DatagramPacket(buffer, RECEIVE_BUFFER_SIZE); socket.receive(packet); msgList.add(packet); } catch (InterruptedIOException e) { break; } catch (IOException ex) { if (!ex.getMessage().equalsIgnoreCase("socket closed")) { LOG.error("Error in UDP server", ex); } } } socket.close(); LOG.info("UDP NAT server closed."); }
From source file:org.springframework.integration.ip.udp.UdpChannelAdapterTests.java
@SuppressWarnings("unchecked") @Test//from w ww .ja v a2 s . com 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())); }