List of usage examples for java.net DatagramPacket getData
public synchronized byte[] getData()
From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationIncomingMessageHandler.java
/** * The main logic of the monitor. Reads in data from the client socket until * the client socket is closed/disconnected. * //from ww w . j a v a2 s . c o m * @see java.lang.Runnable#run() */ public void run() { /* Create a Datagram packet to hold the recieved message */ DatagramPacket pack = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE); /* Should the loop keep running? */ boolean keepRunning = true; /* This part loops until we catch an exception */ while (keepRunning) { /* receive messages on the socket */ try { System.out.println("Attempting to recieve a packet"); newSock.receive(pack); System.out.println("RECIEVED A PACKET OMG"); } catch (IOException e) { e.printStackTrace(); logger.warn(e.getMessage()); } /* put messages into the buffer */ if (pack.getData() != null) { try { // List<byte[]> listOfBytes = this.host.getProtocol() // .removeProtocol(pack.getData()); // for (byte[] b : listOfBytes) { this.host.getReceiveBuffer().addToBuffer(pack.getData()); this.host.setRemoteIPAddress(pack.getAddress().getHostAddress()); this.host.setRemotePort(pack.getPort()); // } } catch (DataBufferInterruptedException e) { /* Thrown because socket was interrupted */ logger.warn(e.getMessage()); keepRunning = false; } // catch (ProtocolValidationException e) { // /* Thrown because of a problem with the protocol */ // logger.warn(e.getMessage()); // } } } }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore// w ww .ja 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.DatagramPacketMulticastSendingHandlerTests.java
@Test public void verifySendMulticast() throws Exception { MulticastSocket socket;//from www. j a va2s.co 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:net.dv8tion.jda.audio.AudioWebSocket.java
private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) { //We will now send a packet to discord to punch a port hole in the NAT wall. //This is called UDP hole punching. try {/*w ww. j a va 2s .c om*/ udpSocket = new DatagramSocket(); //Use UDP, not TCP. //Create a byte array of length 70 containing our ssrc. ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208 buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord. //Construct our packet to be sent loaded with the byte buffer we store the ssrc in. DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(discoveryPacket); //Discord responds to our packet, returning a packet containing our external ip and the port we connected through. DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent. udpSocket.setSoTimeout(1000); udpSocket.receive(receivedPacket); //The byte array returned by discord containing our external ip and the port that we used //to connect to discord with. byte[] received = receivedPacket.getData(); //Example string:" 121.83.253.66 " //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and // the last 2 bytes. Not sure why these exist. The last 2 bytes are the port. More info below. String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces. ourIP = ourIP.substring(0, ourIP.length() - 2); //Removes the port that is stuck on the end of this string. (last 2 bytes are the port) ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short. //Furthermore, it is stored in Little Endian instead of normal Big Endian. //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order) //Then we will need to deal with the fact that the bytes represent an unsigned short. //Java cannot deal with unsigned types, so we will have to promote the short to a higher type. //Options: char or int. I will be doing int because it is just easier to work with. byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size. portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second. //We have now effectively converted from Little Endian -> Big Endian by reversing the order. //For more information on how this is converting from an unsigned short to an int refer to: //http://www.darksleep.com/player/JavaAndUnsignedTypes.html int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned. int secondByte = (0x000000FF & ((int) portBytes[1])); // //Combines the 2 bytes back together. int ourPort = (firstByte << 8) | secondByte; this.address = address; return new InetSocketAddress(ourIP, ourPort); } catch (SocketException e) { return null; } catch (IOException e) { LOG.log(e); return null; } }
From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java
@Test @Ignore/*from ww w . j a va 2 s . c om*/ 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:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {//from ww w .ja va 2 s . co m DatagramSocket socket = new DatagramSocket(32414); socket.setBroadcast(true); String data = "M-SEARCH * HTTP/1.1\r\n\r\n"; DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), useMultiCastAddress(), 32414); // DatagramPacket packet = new DatagramPacket(data.getBytes(), // data.length(), getBroadcastAddress(), 32414); socket.send(packet); Log.d("GDMService", "Search Packet Broadcasted"); byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.setSoTimeout(2000); boolean listening = true; while (listening) { try { socket.receive(packet); String packetData = new String(packet.getData()); if (packetData.contains("HTTP/1.0 200 OK")) { Log.d("GDMService", "PMS Packet Received"); // Broadcast Received Packet Intent packetBroadcast = new Intent(GDMService.MSG_RECEIVED); packetBroadcast.putExtra("data", packetData); packetBroadcast.putExtra("ipaddress", packet.getAddress().toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(packetBroadcast); } } catch (SocketTimeoutException e) { Log.d("GDMService", "Socket Timeout"); socket.close(); listening = false; Intent socketBroadcast = new Intent(GDMService.SOCKET_CLOSED); LocalBroadcastManager.getInstance(this).sendBroadcast(socketBroadcast); } } } catch (IOException e) { Log.e("GDMService", e.toString()); } }
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 w w w .ja va 2s . co m*/ // 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:com.carreygroup.JARVIS.Demon.java
/******************************UDP******************************/ public byte[] ReceviedByUdp() { Log.i("_DEBUG", "ReceviedByUdp!"); byte data[] = new byte[8]; //DatagramPacketDatagramPacket DatagramPacket packet = new DatagramPacket(data, data.length); // //from w w w . jav a 2s . com try { mReceviedSocket.receive(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return packet.getData(); }
From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java
private InetSocketAddress handleUdpDiscovery(InetSocketAddress address, int ssrc) { //We will now send a packet to discord to punch a port hole in the NAT wall. //This is called UDP hole punching. try {/*from ww w. ja v a 2 s .c om*/ udpSocket = new DatagramSocket(); //Use UDP, not TCP. //Create a byte array of length 70 containing our ssrc. ByteBuffer buffer = ByteBuffer.allocate(70); //70 taken from https://github.com/Rapptz/discord.py/blob/async/discord/voice_client.py#L208 buffer.putInt(ssrc); //Put the ssrc that we were given into the packet to send back to discord. //Construct our packet to be sent loaded with the byte buffer we store the ssrc in. DatagramPacket discoveryPacket = new DatagramPacket(buffer.array(), buffer.array().length, address); udpSocket.send(discoveryPacket); //Discord responds to our packet, returning a packet containing our external ip and the port we connected through. DatagramPacket receivedPacket = new DatagramPacket(new byte[70], 70); //Give a buffer the same size as the one we sent. udpSocket.setSoTimeout(1000); udpSocket.receive(receivedPacket); //The byte array returned by discord containing our external ip and the port that we used //to connect to discord with. byte[] received = receivedPacket.getData(); //Example string:" 121.83.253.66 " //You'll notice that there are 4 leading nulls and a large amount of nulls between the the ip and // the last 2 bytes. Not sure why these exist. The last 2 bytes are the port. More info below. String ourIP = new String(receivedPacket.getData());//Puts the entire byte array in. nulls are converted to spaces. ourIP = ourIP.substring(4, ourIP.length() - 2); //Removes the SSRC of the answer package and the port that is stuck on the end of this string. (last 2 bytes are the port) ourIP = ourIP.trim(); //Removes the extra whitespace(nulls) attached to both sides of the IP //The port exists as the last 2 bytes in the packet data, and is encoded as an UNSIGNED short. //Furthermore, it is stored in Little Endian instead of normal Big Endian. //We will first need to convert the byte order from Little Endian to Big Endian (reverse the order) //Then we will need to deal with the fact that the bytes represent an unsigned short. //Java cannot deal with unsigned types, so we will have to promote the short to a higher type. //Options: char or int. I will be doing int because it is just easier to work with. byte[] portBytes = new byte[2]; //The port is exactly 2 bytes in size. portBytes[0] = received[received.length - 1]; //Get the second byte and store as the first portBytes[1] = received[received.length - 2]; //Get the first byte and store as the second. //We have now effectively converted from Little Endian -> Big Endian by reversing the order. //For more information on how this is converting from an unsigned short to an int refer to: //http://www.darksleep.com/player/JavaAndUnsignedTypes.html int firstByte = (0x000000FF & ((int) portBytes[0])); //Promotes to int and handles the fact that it was unsigned. int secondByte = (0x000000FF & ((int) portBytes[1])); // //Combines the 2 bytes back together. int ourPort = (firstByte << 8) | secondByte; this.address = address; return new InetSocketAddress(ourIP, ourPort); } catch (SocketException e) { return null; } catch (IOException e) { return null; } }
From source file:org.openhab.binding.hexabus.internal.HexaBusBinding.java
/** * Gets the consumption of the targetted plug in Watt. * //from w w w. j a v a 2s . c om * @param target_ip the ip of the targetted plug * * @return the power consumption in Watt * @throws IOException */ private int getConsumption(InetAddress target_ip) { jackdaw_sock.connect(target_ip, PLUG_PORT); byte[] bmsg = HexBin.decode(GET_MESSAGE); byte[] receiveData = new byte[1024]; DatagramPacket outgoing = new DatagramPacket(bmsg, bmsg.length); DatagramPacket incoming = new DatagramPacket(receiveData, HEXABUS_RESPONSE_LENGTH); try { jackdaw_sock.send(outgoing); } catch (IOException e) { logger.debug("Send failed on Jackdaw Socket while trying to GET consumption!"); e.printStackTrace(); } try { jackdaw_sock.receive(incoming); } catch (IOException e) { logger.debug("Receive failed on Jackdaw Socket while trying to GET consumption!"); e.printStackTrace(); } byte[] data = incoming.getData(); // checks if no data was received. if (data.length == 0) { logger.debug("No data was transmitted in getConsumption!"); } // the last four bytes contain the consumption integer byte[] temp = { data[11], data[12], data[13], data[14] }; ByteBuffer wrapped = ByteBuffer.wrap(temp); int val = wrapped.getInt(); logger.debug("Power Consumption of hpp: " + val); return val; }