List of usage examples for java.net DatagramPacket getOffset
public synchronized int getOffset()
From source file:org.zxg.network.dhtcrawler.Crawler.java
@Override protected UdpMsg recvUdp() throws IOException { byte[] buffer = new byte[65536]; DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length); socket.receive(datagramPacket);//from w ww . j av a2 s . c o m UdpMsg msg = new UdpMsg(); msg.data = new byte[datagramPacket.getLength()]; System.arraycopy(datagramPacket.getData(), datagramPacket.getOffset(), msg.data, 0, datagramPacket.getLength()); InetSocketAddress socketAddress = (InetSocketAddress) datagramPacket.getSocketAddress(); msg.addr = new Addr(socketAddress.getHostString(), socketAddress.getPort()); return msg; }
From source file:org.apache.jmeter.JMeter.java
private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) { byte[] buf = new byte[80]; System.out.println(//from www .j a v a 2 s . com "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort()); DatagramPacket request = new DatagramPacket(buf, buf.length); try { while (true) { socket.receive(request); InetAddress address = request.getAddress(); // Only accept commands from the local host if (address.isLoopbackAddress()) { String command = new String(request.getData(), request.getOffset(), request.getLength(), "ASCII"); System.out.println("Command: " + command + " received from " + address); log.info("Command: " + command + " received from " + address); if (command.equals("StopTestNow")) { for (JMeterEngine engine : engines) { engine.stopTest(true); } } else if (command.equals("Shutdown")) { for (JMeterEngine engine : engines) { engine.stopTest(false); } } else if (command.equals("HeapDump")) { HeapDumper.dumpHeap(); } else { System.out.println("Command: " + command + " not recognised "); } } } } catch (Exception e) { System.out.println(e); } finally { socket.close(); } }
From source file:udpserver.UDPui.java
private void tempReceiveUDP() { background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }/*w w w .ja v a2 s .c om*/ // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String word = serverSocket.getInetAddress().toString(); // Integer count = counting.get(word); // if (count == null) { // counting.put(word, 1); // } // else { // counting.put(word, count + 1); // } boolean looprun = true; String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); // System.out.println(message); while (looprun) { if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); Integer count = counting.get(word); if (count == null) { counting.put(word, 2); } else { counting.put(word, count + 1); } // System.out.println(count + ":" + message); } else { looprun = false; } } if (message.equals("end")) { valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); //end send back to mobile // count = 1; // break; counting.remove(word); } else if (available) { // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); } } // } // } } }; backgroundProcess = new Thread(background); }
From source file:udpserver.UDPui.java
private void receiveUDP() { countSeparate = new ArrayList<>(); background = new Runnable() { public void run() { try { serverSocket = new DatagramSocket(9876); } catch (SocketException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); }//from ww w . ja v a 2s . c om // while (true) { // byte[] receiveData = new byte[1024]; // DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); //<editor-fold defaultstate="collapsed" desc="Start timer after receive a packet"> // try { // serverSocket.receive(receivePacket); // series.clear(); // valuePane.setText(""); available = true; // System.out.println(available); // } catch (IOException ex) { // Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); // } // Timer timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { // available = false; // System.out.println("Finish Timer"); // } // }, 1 * 1000); //</editor-fold> // if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) { // int count = 1; // while (available) { while (true) { try { byte[] receiveData = new byte[total_byte]; byte[] sendData = new byte[32]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String word = receivePacket.getAddress().getHostAddress(); System.out.println(word); String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); boolean looprun = true; // System.out.println(message); while (looprun) { Integer countt = counting.get(word); if (message.contains("&")) { message = message.substring(message.indexOf("&") + 1); // count++; // Integer countt = counting.get(word); if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } // System.out.println(count + ":" + message); } else { if (countt == null) { counting.put(word, 1); } else { counting.put(word, countt + 1); } System.out.println(counting.get(word)); looprun = false; } } if (message.contains("start")) { if (counting.get(word) != null) { counting.remove(word); } } else if (message.contains("end")) { message = message.substring(message.indexOf("end") + 3); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); //send back to mobile InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // String capitalizedSentence = count + ""; String capitalizedSentence = counting.get(word) + ""; sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); String content = IPAddress.getCanonicalHostName() + "," + timeStamp + "," + (counting.get(word) - 1) + "," + message; saveFile(content); //end send back to mobile // System.out.println(counting.get(word)); // count = 1; counting.remove(word); // break; } else if (available) { //<editor-fold defaultstate="collapsed" desc="check hasmap key"> // if (hm.size() > 0 && hm.containsKey(serverSocket.getInetAddress().getHostAddress())) { // hm.put(foundKey, new Integer(((int) hm.get(foundKey)) + 1)); // hm.put(serverSocket.getInetAddress().getHostAddress(), new Integer(((int) hm.get(serverSocket.getInetAddress().getHostAddress())) + 1)); // } else { // hm.put(serverSocket.getInetAddress().getHostAddress(), 1); // hm.entrySet().add(new Map<String, Integer>.Entry<String, Integer>()); // } //</editor-fold> // series.add(count, Double.parseDouble(message)); // valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n"); // valuePane.setCaretPosition(valuePane.getDocument().getLength()); // count++; } } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); valuePane.setText(valuePane.getText().toString() + "IOException" + "\n"); } } // valuePane.setText(valuePane.getText().toString() + "Out of while loop" + "\n"); // } // } } private void saveFile(String content) { try { File desktop = new File(System.getProperty("user.home"), "Desktop"); File file = new File(desktop.getAbsoluteFile() + "/udp.csv"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fop = new FileOutputStream(file, true); fop.write((content + "\n").getBytes()); fop.flush(); fop.close(); // String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime()); // valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } catch (IOException ex) { Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex); String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss") .format(Calendar.getInstance().getTime()); valuePane.setText(valuePane.getText().toString() + timeStamp + "\n"); } } }; backgroundProcess = new Thread(background); }
From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java
@Test public void verifySendMulticast() throws Exception { MulticastSocket socket;/*from w w w . j av a2s . c o m*/ try { socket = new MulticastSocket(); } catch (Exception e) { return; } final int testPort = socket.getLocalPort(); final String multicastAddress = this.multicastRule.getGroup(); final String payload = "foo"; final CountDownLatch listening = new CountDownLatch(2); final CountDownLatch received = new CountDownLatch(2); Runnable catcher = () -> { try { byte[] buffer = new byte[8]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); listening.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket1.receive(receivedPacket); socket1.close(); 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)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); received.countDown(); } catch (Exception e) { listening.countDown(); e.printStackTrace(); } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); assertTrue(listening.await(10000, TimeUnit.MILLISECONDS)); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); handler.setBeanFactory(mock(BeanFactory.class)); handler.setLocalAddress(this.multicastRule.getNic()); handler.afterPropertiesSet(); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(received.await(10000, TimeUnit.MILLISECONDS)); handler.stop(); socket.close(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/*w ww.j a v a2 s . co m*/ public void verifySendMulticast() throws Exception { final int testPort = SocketUtils.findAvailableUdpSocket(); final String multicastAddress = "225.6.7.8"; final String payload = "foo"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[8]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); 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)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(3000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/*from www. ja v a2 s. com*/ public void verifySendMulticastWithAcks() throws Exception { final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2); final int testPort = openPorts.get(0); final int ackPort = openPorts.get(1); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(2); Runnable catcher = new Runnable() { public void run() { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket = new MulticastSocket(testPort); InetAddress group = InetAddress.getByName(multicastAddress); socket.joinGroup(group); latch1.countDown(); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket.receive(receivedPacket); socket.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress("localHost", ackPort)); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); latch2.countDown(); } catch (Exception e) { noMulticast = true; latch1.countDown(); e.printStackTrace(); } } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); latch1.await(3000, TimeUnit.MILLISECONDS); if (noMulticast) { return; } MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", ackPort, 500000); handler.setMinAcksForSuccess(2); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); handler.shutDown(); }
From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java
@Test public void verifySendMulticastWithAcks() throws Exception { MulticastSocket socket;/*from w ww . j a v a 2 s. c o m*/ try { socket = new MulticastSocket(); } catch (Exception e) { return; } final int testPort = socket.getLocalPort(); final AtomicInteger ackPort = new AtomicInteger(); final String multicastAddress = "225.6.7.8"; final String payload = "foobar"; final CountDownLatch listening = new CountDownLatch(2); final CountDownLatch ackListening = new CountDownLatch(1); final CountDownLatch ackSent = new CountDownLatch(2); Runnable catcher = () -> { try { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); socket1.setSoTimeout(8000); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); listening.countDown(); assertTrue(ackListening.await(10, TimeUnit.SECONDS)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet"); socket1.receive(receivedPacket); socket1.close(); byte[] src = receivedPacket.getData(); int length = receivedPacket.getLength(); int offset = receivedPacket.getOffset(); byte[] dest = new byte[6]; System.arraycopy(src, offset + length - 6, dest, 0, 6); assertEquals(payload, new String(dest)); LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet"); DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); mapper.setAcknowledge(true); mapper.setLengthCheck(true); Message<byte[]> message = mapper.toMessage(receivedPacket); Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, new InetSocketAddress(multicastRule.getNic(), ackPort.get())); DatagramSocket out = new DatagramSocket(); out.send(ackPack); LogFactory.getLog(getClass()) .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress()); out.close(); ackSent.countDown(); socket1.close(); } catch (Exception e) { listening.countDown(); e.printStackTrace(); } }; Executor executor = Executors.newFixedThreadPool(2); executor.execute(catcher); executor.execute(catcher); assertTrue(listening.await(10000, TimeUnit.MILLISECONDS)); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", 0, 10000); handler.setLocalAddress(this.multicastRule.getNic()); handler.setMinAcksForSuccess(2); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); handler.start(); waitAckListening(handler); ackPort.set(handler.getAckPort()); ackListening.countDown(); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS)); handler.stop(); socket.close(); }
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 ww w. jav a2 s . c o m*/ 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.lockss.test.LockssTestCase.java
/** * Asserts that the two DatagramPackets have equal contents * @param expected the expected value/*from ww w. ja va 2s. c om*/ * @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())); }