List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:org.eredlab.g4.ccl.net.tftp.TFTP.java
/*** * Initializes the internal buffers. Buffers are used by * {@link #bufferedSend bufferedSend() } and * {@link #bufferedReceive bufferedReceive() }. This * method must be called before calling either one of those two * methods. When you finish using buffered operations, you must * call {@link #endBufferedOps endBufferedOps() }. ***///from w ww . j a v a 2s.c o m public final void beginBufferedOps() { __receiveBuffer = new byte[PACKET_SIZE]; __receiveDatagram = new DatagramPacket(__receiveBuffer, __receiveBuffer.length); _sendBuffer = new byte[PACKET_SIZE]; __sendDatagram = new DatagramPacket(_sendBuffer, _sendBuffer.length); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Creates a new job manager lookup request packet. * // w ww .j a va 2s. com * @param magicNumber * the magic number to identify this discovery service * @return a new job manager lookup request packet */ private static DatagramPacket createJobManagerLookupRequestPacket(final int magicNumber) { final byte[] bytes = new byte[12]; integerToByteArray(magicNumber, MAGIC_NUMBER_OFFSET, bytes); integerToByteArray(generateRandomPacketID(), PACKET_ID_OFFSET, bytes); integerToByteArray(JM_LOOKUP_REQUEST_ID, PACKET_TYPE_ID_OFFSET, bytes); return new DatagramPacket(bytes, bytes.length); }
From source file:net.sbbi.upnp.DiscoveryAdvertisement.java
private void startMultiCastSocket() throws IOException { skt = new java.net.MulticastSocket(null); skt.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), Discovery.SSDP_PORT)); skt.setTimeToLive(Discovery.DEFAULT_TTL); skt.setSoTimeout(DEFAULT_TIMEOUT); skt.joinGroup(InetAddress.getByName(Discovery.SSDP_IP)); byte[] buf = new byte[2048]; input = new DatagramPacket(buf, buf.length); }
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); }/* w w w .jav a 2 s . com*/ // 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.openhab.binding.hexabus.internal.HexaBusBinding.java
/** * Method to send UDP packets containing commands to the HexaBus Plugs * //from w w w . ja va 2s .c om * @param target Target IP address * @param cmd A string which represents a command */ private void switchPlug(InetAddress target_ip, Command command) { logger.debug("switchPlug() called!"); jackdaw_sock.connect(target_ip, PLUG_PORT); String msg = ""; if (command.equals(ON)) { msg = ON_MESSAGE; } else if (command.equals(OFF)) { msg = OFF_MESSAGE; } else { logger.debug("Unrecognized cmd-String: " + command.toString()); return; } byte[] bmsg = HexBin.decode(msg); logger.debug("InetAddress of Plug: " + target_ip); logger.debug("bmsg: " + bmsg.toString()); DatagramPacket packet = new DatagramPacket(bmsg, bmsg.length); try { jackdaw_sock.send(packet); } catch (IOException e) { e.printStackTrace(); logger.debug("Could not send command packet in switchPlug()!"); } }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Creates a new job manager lookup reply packet. * /*from w ww. j av a2 s .c o m*/ * @param ipcPort * the port of the job manager's IPC server * @param magicNumber * the magic number to identify this discovery service * @return a new job manager lookup reply packet */ private static DatagramPacket createJobManagerLookupReplyPacket(final int ipcPort, final int magicNumber) { final byte[] bytes = new byte[16]; integerToByteArray(magicNumber, MAGIC_NUMBER_OFFSET, bytes); integerToByteArray(generateRandomPacketID(), PACKET_ID_OFFSET, bytes); integerToByteArray(JM_LOOKUP_REPLY_ID, PACKET_TYPE_ID_OFFSET, bytes); integerToByteArray(ipcPort, PAYLOAD_OFFSET, bytes); return new DatagramPacket(bytes, bytes.length); }
From source file:com.clustercontrol.agent.Agent.java
/** * ??awakeAgent?/*from ww w . j ava 2 s. c om*/ * Agent.properties???UDP?24005??????????(releaseLatch) * ????ReceiveTopic????Topic???? */ public void waitAwakeAgent() { final int BUFSIZE = 1; byte[] buf = new byte[BUFSIZE]; InetAddress cAddr; // ??IP int cPort; // ??? DatagramSocket sock = null; boolean flag = true; int port = 24005; int awakeDelay = 1000; try { String awakeDelayStr = AgentProperties.getProperty("awake.delay", Integer.toString(1000)); awakeDelay = Integer.parseInt(awakeDelayStr); m_log.info("awake.delay = " + awakeDelay + " msec"); } catch (NumberFormatException e) { m_log.error("awake.delay", e); } while (true) { /* * UDP???flag?true?? * ?????flag?false?????getTopic(releaseLatch)? * * UDP???????getTopic???????? * ?????? */ try { if (sock != null && port != awakePort) { sock.close(); sock = null; } if (sock == null || !sock.isBound()) { port = awakePort; sock = new DatagramSocket(port); sock.setSoTimeout(awakeDelay); } DatagramPacket recvPacket = new DatagramPacket(buf, BUFSIZE); sock.receive(recvPacket); cAddr = recvPacket.getAddress(); cPort = recvPacket.getPort(); flag = true; m_log.info("waitAwakeAgent (" + cAddr.getHostAddress() + " onPort=" + cPort + ") buf.length=" + buf.length); } catch (SocketTimeoutException e) { if (flag) { m_log.info("waitAwakeAgent packet end"); m_receiveTopic.releaseLatch(); flag = false; } } catch (Exception e) { String msg = "waitAwakeAgent port=" + awakePort + ", " + e.getClass().getSimpleName() + ", " + e.getMessage(); if (e instanceof BindException) { m_log.warn(msg); } else { m_log.warn(msg, e); } try { Thread.sleep(60 * 1000); } catch (InterruptedException e1) { m_log.warn(e1, e1); } } } }
From source file:net.dv8tion.jda.core.audio.AudioConnection.java
private synchronized void setupReceiveThread() { if (receiveThread == null) { receiveThread = new Thread(AudioManagerImpl.AUDIO_THREADS, threadIdentifier + " Receiving Thread") { @Override//w w w . j av a2 s. co m public void run() { try { udpSocket.setSoTimeout(1000); } catch (SocketException e) { LOG.log(e); } while (!udpSocket.isClosed() && !this.isInterrupted()) { DatagramPacket receivedPacket = new DatagramPacket(new byte[1920], 1920); try { udpSocket.receive(receivedPacket); if (receiveHandler != null && (receiveHandler.canReceiveUser() || receiveHandler.canReceiveCombined()) && webSocket.getSecretKey() != null) { if (!couldReceive) { couldReceive = true; sendSilentPackets(); } AudioPacket decryptedPacket = AudioPacket.decryptAudioPacket(receivedPacket, webSocket.getSecretKey()); int ssrc = decryptedPacket.getSSRC(); final long userId = ssrcMap.get(ssrc); Decoder decoder = opusDecoders.get(ssrc); if (userId == ssrcMap.getNoEntryValue()) { byte[] audio = decryptedPacket.getEncodedAudio(); //If the bytes are silence, then this was caused by a User joining the voice channel, // and as such, we haven't yet received information to pair the SSRC with the UserId. if (!Arrays.equals(audio, silenceBytes)) LOG.debug("Received audio data with an unknown SSRC id. Ignoring"); continue; } if (decoder == null) { decoder = new Decoder(ssrc); opusDecoders.put(ssrc, decoder); } if (!decoder.isInOrder(decryptedPacket.getSequence())) { LOG.trace("Got out-of-order audio packet. Ignoring."); continue; } User user = getJDA().getUserById(userId); if (user == null) LOG.warn( "Received audio data with a known SSRC, but the userId associate with the SSRC is unknown to JDA!"); else { // if (decoder.wasPacketLost(decryptedPacket.getSequence())) // { // LOG.debug("Packet(s) missed. Using Opus packetloss-compensation."); // short[] decodedAudio = decoder.decodeFromOpus(null); // receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio)); // } short[] decodedAudio = decoder.decodeFromOpus(decryptedPacket); //If decodedAudio is null, then the Opus decode failed, so throw away the packet. if (decodedAudio == null) { LOG.trace( "Received audio data but Opus failed to properly decode, instead it returned an error"); } else { if (receiveHandler.canReceiveUser()) { receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio)); } if (receiveHandler.canReceiveCombined()) { Queue<Pair<Long, short[]>> queue = combinedQueue.get(user); if (queue == null) { queue = new ConcurrentLinkedQueue<>(); combinedQueue.put(user, queue); } queue.add(Pair.<Long, short[]>of(System.currentTimeMillis(), decodedAudio)); } } } } else if (couldReceive) { couldReceive = false; sendSilentPackets(); } } catch (SocketTimeoutException e) { //Ignore. We set a low timeout so that we wont block forever so we can properly shutdown the loop. } catch (SocketException e) { //The socket was closed while we were listening for the next packet. //This is expected. Ignore the exception. The thread will exit during the next while // iteration because the udpSocket.isClosed() will return true. } catch (Exception e) { LOG.log(e); } } } }; receiveThread.setDaemon(true); receiveThread.start(); } if (receiveHandler.canReceiveCombined()) { setupCombinedExecutor(); } }
From source file:org.openhab.binding.hexabus.internal.HexaBusBinding.java
/** * Gets the consumption of the targetted plug in Watt. * /*w ww. j a v a2s .co m*/ * @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; }
From source file:org.eredlab.g4.ccl.net.tftp.TFTP.java
/*** * Receives a TFTPPacket./* www . ja v a2 s.com*/ * <p> * @return The TFTPPacket received. * @exception InterruptedIOException If a socket timeout occurs. The * Java documentation claims an InterruptedIOException is thrown * on a DatagramSocket timeout, but in practice we find a * SocketException is thrown. You should catch both to be safe. * @exception SocketException If a socket timeout occurs. The * Java documentation claims an InterruptedIOException is thrown * on a DatagramSocket timeout, but in practice we find a * SocketException is thrown. You should catch both to be safe. * @exception IOException If some other I/O error occurs. * @exception TFTPPacketException If an invalid TFTP packet is received. ***/ public final TFTPPacket receive() throws IOException, InterruptedIOException, SocketException, TFTPPacketException { DatagramPacket packet; packet = new DatagramPacket(new byte[PACKET_SIZE], PACKET_SIZE); _socket_.receive(packet); return TFTPPacket.newTFTPPacket(packet); }