List of usage examples for java.net DatagramPacket getData
public synchronized byte[] getData()
From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java
public void run() { InetAddress group = null;//from ww w.ja v a 2s.com try { group = InetAddress.getByName("239.255.255.250"); skt = new java.net.MulticastSocket(1900); skt.setInterface(bindAddress.getAddress()); skt.joinGroup(group); } catch (IOException ex) { log.error("Error during multicast socket creation, thread cannot start", ex); return; } isRunning = true; while (isRunning) { try { byte[] buffer = new byte[4096]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, bindAddress.getPort()); skt.receive(packet); String received = new String(packet.getData(), 0, packet.getLength()); if (log.isDebugEnabled()) log.debug("Received message:\n" + received); HttpRequest req = new HttpRequest(received); if (req.getHttpCommand().equals("M-SEARCH")) { String man = req.getHTTPHeaderField("MAN"); if (man.equals("\"ssdp:discover\"")) { String searchTarget = req.getHTTPHeaderField("ST"); // TODO check ALL devices search target //if ( searchTarget.equals( Discovery.ALL_DEVICES ) ) { if (searchTarget.equals(Discovery.ROOT_DEVICES)) { java.net.MulticastSocket multi = new java.net.MulticastSocket(); multi.setInterface(bindAddress.getAddress()); for (Iterator i = handledDevices.iterator(); i.hasNext();) { UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next(); List packets = getReplyMessages(dv, false, dv.getSSDPAliveDelay()); for (int z = 0; z < packets.size(); z++) { String pack = (String) packets.get(z); if (log.isDebugEnabled()) log.debug("Sending http reply message on " + packet.getAddress() + ":" + packet.getPort() + " multicast address:\n" + pack.toString()); byte[] pk = pack.getBytes(); multi.setTimeToLive(dv.getSSDPTTL()); multi.send(new DatagramPacket(pk, pk.length, packet.getAddress(), packet.getPort())); } } multi.close(); } else { // TODO check a specific search target } } } } catch (IOException ex) { if (isRunning) { log.error("Error during multicast socket IO operations", ex); } } } }
From source file:org.psit.transwatcher.TransWatcher.java
private String connectAndGetCardIP() { DatagramSocket clientSocket = null, serverSocket = null; try {/*from w w w .j a va 2 s . c o m*/ String broadcastIP = getBroadcastIP(); setState(broadcastIP == null ? State.NO_WIFI : State.SEARCHING_CARD); notifyMessage("BroadcastIP: " + broadcastIP); // send out broadcast clientSocket = new DatagramSocket(58255); InetAddress IPAddress = InetAddress.getByName(broadcastIP); byte[] sendData = "".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 55777); clientSocket.send(sendPacket); clientSocket.close(); serverSocket = new DatagramSocket(58255); byte[] receiveData = new byte[256]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.setSoTimeout(3000); serverSocket.receive(receivePacket); serverSocket.close(); notifyMessage("Packet received: " + new String(receiveData)); if (new String(receivePacket.getData()).indexOf("Transcend WiFiSD") >= 0) return receivePacket.getAddress().getHostAddress(); } catch (Exception ex) { notifyMessage("Card handshake unsuccessful. "); notifyException(ex); } finally { if (clientSocket != null) clientSocket.close(); if (serverSocket != null) serverSocket.close(); } return null; }
From source file:Network.Network.java
private String discoverUDPServer() { DatagramSocket c;/*from w ww. ja v a2 s . c o m*/ String foundIP = null; // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_BATTLESHIPSERVER_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 8888); c.send(sendPacket); System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } /*// Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } }*/ System.out.println(getClass().getName() + ">>> Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response System.out.println(getClass().getName() + ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_BATTLESHIPSERVER_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) foundIP = receivePacket.getAddress().getHostAddress(); } //Close the port! c.close(); } catch (IOException ex) { Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex); } return foundIP; }
From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java
/** * Discovery Process to identify Clusters with in * network.//from w ww .j a v a 2s. c o m * * @throws IOException if occurred during operation */ private void doDiscover() throws IOException { // Send Request byte[] greet = GREET_MSG.getBytes("UTF-8"); DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT); MulticastSocket reqSock = new MulticastSocket(); reqSock.send(request); // Wait for Response MulticastSocket resSock = new MulticastSocket(SERVICE_PORT); resSock.joinGroup(SERVICE_RESPONSE_IP); // 9 = # of bytes for an IP Address + 5 byte port DatagramPacket response = new DatagramPacket(new byte[9], 9); // Receive resSock.setSoTimeout((int) TIMEOUT); try { resSock.receive(response); } catch (SocketTimeoutException e) { log.debug("[MulticastDiscovery] Receive Timeout"); return; } byte[] data = response.getData(); byte[] ipBytes = Arrays.copyOfRange(data, 0, 4); byte[] portBytes = Arrays.copyOfRange(data, 4, 9); InetAddress ip = InetAddress.getByAddress(ipBytes); StringBuilder sb = new StringBuilder(ip.getHostAddress()); sb.append(":"); for (byte b : portBytes) { sb.append(b); } this.cluster = sb.toString(); }
From source file:org.openhab.binding.yeelight.internal.YeelightBinding.java
private void receiveData(MulticastSocket socket, DatagramPacket dgram) { try {/*from ww w . j ava 2 s. c o m*/ while (true) { socket.receive(dgram); String sentence = new String(dgram.getData(), 0, dgram.getLength()); logger.debug("Yeelight received packet: {}", sentence); if (isOKPacket(sentence) || isNotifyPacket(sentence)) { String[] lines = sentence.split("\n"); String id = ""; String location = ""; String model = ""; String support = ""; for (String line : lines) { line = line.replace("\r", ""); line = line.replace("\n", ""); if (line.startsWith("id: ")) id = line.substring(4); else if (line.startsWith("Location: ")) location = line.substring(10); else if (line.startsWith("model: ")) model = line.substring(7); else if (line.startsWith("support: ")) support = line.substring(9); } if (!id.equals("") && !devices.containsKey(id)) { YeelightDevice device = new YeelightDevice(id, location, model, support); devices.put(id, device); logger.info("Found Yeelight device :\n{}", device.toString()); } } } } catch (IOException e) { logger.error(e.toString()); } }
From source file:Networking.Networking.java
/** * Receives data via UDP on {@see #udpSocket}. * @return {@code DatagramPacket} the packet received. *///from ww w . ja v a 2s .c om private DatagramPacket recvUDP() { try { // while(true){ DatagramPacket receivePacket = new DatagramPacket(udpInData, udpInData.length); // System.out.println("Listen UDP on " + udpSocket.getLocalSocketAddress().toString()); udpSocket.receive(receivePacket); // System.out.println("Listen UDP on " + udpSocket.getLocalAddress().toString()); String msg = new String(receivePacket.getData()); // System.out.println("recvUDP: " + msg); // System.out.println(" at " + udpSocket.getLocalSocketAddress().toString()); return receivePacket; } catch (IOException ex) { Logger.getLogger(Networking.class.getName()).log(Level.SEVERE, null, ex); System.err.println("exception while broadcasting UDP"); } return null; }
From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java
/** * Tests turning on the UDPCommunication while it is off. * /*from w ww .j a v a2 s . c o m*/ * */ public void testTurnOnWhenOff() { /* Data to send */ byte[] dataToSend = message.getBytes(); /* Error code -- gets modified if exceptions occur. */ boolean error = false; /* Attempt to connect to the specified IP/Port using UDP */ this.udpComm.turnOn(); /* Allow server socket to fully start */ synchronized (this) { try { this.wait(1000); } catch (InterruptedException e2) { /* Do nothing */ } this.notifyAll(); } /* Make a client */ DatagramSocket clientSocket = null; try { clientSocket = new DatagramSocket(this.udpComm.getRemotePort()); } catch (SocketException e) { logger.debug(this.getName() + ": " + e.getMessage()); error = true; } /* Send out a packet of data */ try { this.udpComm.getSendBuffer().addToBuffer(dataToSend); } catch (DataBufferInterruptedException dbie) { logger.debug(this.getName() + ": " + dbie.getMessage()); error = true; } /* Receive the packet of data */ if (clientSocket != null) { /* Set a timeout for receiving data */ try { clientSocket.setSoTimeout(1000); } catch (SocketException e) { logger.debug(this.getName() + ": " + e.getMessage()); error = true; } /* Make a new packet to hold the received data */ DatagramPacket dataPacket = new DatagramPacket(new byte[1024], 1024); /* Attempt to receive the data */ try { clientSocket.receive(dataPacket); } catch (IOException e) { logger.debug(this.getName() + ": " + e.getMessage()); error = true; } /* Check that the data was received succesfully */ if (!error) { logger.debug("Client received: " + new String(dataPacket.getData())); } else { logger.debug(this.getName() + ": client did not receive message."); error = true; } clientSocket.disconnect(); clientSocket.close(); clientSocket = null; } /* Check to see if any errors happened. */ assertFalse(error); }
From source file:br.com.skylane.voicer.rtp.RtpMediaDecoder.java
@Override public void processDatagramPacket(DatagramPacket pct) { if (playerThread == null || decoder == null) return;/*w ww .java2 s. co m*/ ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(pct.getData(), 0, pct.getLength()); DataPacket dp = DataPacket.decode(buffer); dp.setTimestamp(dp.getTimestamp() * 1000L / 90L); if (lastSequenceNumberIsValid && (lastSequenceNumber + 1) != dp.getSequenceNumber()) { lastSequenceNumber = dp.getSequenceNumber(); return; // droppack } H264Packet h264Packet = new H264Packet(dp); if (!decoderInicializado && !h264Packet.h264NalType.equals(NalType.STAPA)) return; switch (h264Packet.h264NalType) { case FULL: inputBufIndex = decoder.dequeueInputBuffer(-1); inputBuf = inputBuffers[inputBufIndex]; inputBuf.clear(); inputBuf.put(dp.getDataAsArray()); playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 1, inputBufIndex); break; case FUA: if (h264Packet.isStart()) { if (RtpMediaDecoder.DEBUGGING) { log.info("FU-A start found. Starting new frame"); } inputBufIndex = decoder.dequeueInputBuffer(-1); inputBuf = inputBuffers[inputBufIndex]; inputBuf.clear(); currentTimestamp = dp.getTimestamp(); } // if we don't have a buffer here, it means that we skipped the start packet for this // NAL unit, so we can't do anything other than discard everything else if (currentTimestamp != 0) { // Did we miss packets in the middle of a frame transition? // In that case, I don't think there's much we can do other than flush our buffer // and discard everything until the next buffer if (dp.getTimestamp() != currentTimestamp) { if (RtpMediaDecoder.DEBUGGING) { log.warn("Non-consecutive timestamp found"); } } else { inputBuf.put(dp.getDataAsArray(), 2, dp.getDataSize() - 2); } if (h264Packet.isEnd()) { if (RtpMediaDecoder.DEBUGGING) { log.info("FU-A end found. Sending frame!"); } playerThread.decodeFrame(inputBuf, currentTimestamp, 0, inputBufIndex); currentTimestamp = 0; } } break; case STAPA: decoderInicializado = true; inputBufIndex = decoder.dequeueInputBuffer(-1); inputBuf = inputBuffers[inputBufIndex]; inputBuf.clear(); int idx = VoicerHelper.indexOf(dp.getDataAsArray(), new byte[] { 0, 0, 0, 1 }, 4); inputBuf.put(dp.getDataAsArray(), 1, idx - 1); playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 0, inputBufIndex); inputBufIndex = decoder.dequeueInputBuffer(-1); inputBuf = inputBuffers[inputBufIndex]; inputBuf.clear(); inputBuf.put(dp.getDataAsArray(), idx, dp.getDataSize() - idx); playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 0, inputBufIndex); break; case UNKNOWN: break; default: break; } lastSequenceNumber = dp.getSequenceNumber(); lastSequenceNumberIsValid = true; /*android.util.Log.d("VOICER", new String("<< Received: " + pct.getLength())); android.util.Log.d("VOICER", "<< HEX " + VoicerHelper.converteDadosBinariosParaStringHexa(dp.getDataAsArray())); android.util.Log.d("VOICER", "<< Sequence # " + dp.getSequenceNumber());*/ /*String str = ""; for (int i=0; i<pct.getLength(); i++) str+=pct.getData()[i] + ":"; */ //android.util.Log.d(VoicerHelper.TAG, "<< #" + dp.getSequenceNumber() + " length " + dp.getDataSize()); }
From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java
@Override public void run() { if (parent.getRemote() == null) { throw new IllegalArgumentException("No user data set for remote user"); }/*from w ww . ja va2s .c o m*/ logger.info("Started listening to port: " + port); while (running && channel.isBound()) { byte[] bt = new byte[bufferSize]; try { if (mode == ConnectionMode.BINDING) { logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - " + channel.getPort()); Thread.sleep(5); //No reason to hammer on this DatagramPacket packet = new DatagramPacket(bt, 0, bt.length); channel.receive(packet); SocketAddress currentSender = packet.getSocketAddress(); sender = currentSender; byte[] data = Arrays.copyOf(packet.getData(), packet.getLength()); logger.info("Received data: " + Hex.encodeHexString(data) + " on " + channel.getLocalSocketAddress() + " - " + channel.getPort()); byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(), parent.getLocal().getPassword(), (InetSocketAddress) currentSender); ByteBuffer outData = ByteBuffer.wrap(out); logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender); DatagramPacket pc = new DatagramPacket(out, 0, out.length); pc.setSocketAddress(sender); channel.send(pc); this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode logger.info("-> DTLS handshake"); } else if (mode == ConnectionMode.HANDSHAKE) { Thread.sleep(5); logger.info("In handshake mode: "); if (transport == null) { channel.connect(sender); /** * {@link NioUdpTransport} might replace the {@link UDPTransport} here. * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a> */ transport = serverProtocol.accept(dtlsServer, new DtlsMuxStunTransport(parent, channel, MTU)); } sctpService = new SCTPImpl(this); mode = ConnectionMode.TRANSFER; logger.info("-> SCTP mode"); } else if (mode == ConnectionMode.TRANSFER) { /** * Here we receive message and put them to a worker thread for handling * If the output of handling the message is a message, then we send those * using the same thread. */ byte[] buf = new byte[transport.getReceiveLimit()]; int length = transport.receive(buf, 0, buf.length, waitMillis); if (length >= 0) { byte[] handled = Arrays.copyOf(buf, length); workPool.submit(() -> { try { List<byte[]> data = sctpService.handleRequest(handled); data.forEach(this::putDataOnWire); } catch (Exception e) { logger.error("Failed handling message: ", e); } }); logger.debug("Input: " + Hex.encodeHexString(handled)); } } } catch (Exception e) { logger.error("Com error:", e); logger.info("Shutting down, we cannot continue here"); running = false; //Need to quit channel now } } workPool.shutdown(); }
From source file:org.lwes.listener.DatagramEnqueuer.java
/** * While running, repeatedly read datagrams and insert them into the queue along with the * receipt time and other metadata.// w w w . j ava 2 s . co m */ @Override public void run() { running = true; while (running) { try { DatagramPacket datagram = new DatagramPacket(buffer, buffer.length); socket.receive(datagram); if (log.isTraceEnabled()) { log.trace("Received datagram: " + datagram); } /* we record the time *after* the receive because it blocks */ long receiptTime = System.currentTimeMillis(); /* copy the data into a tight buffer so we can release the loose buffer */ final byte[] tightBuffer = new byte[datagram.getLength()]; System.arraycopy(datagram.getData(), 0, tightBuffer, 0, tightBuffer.length); datagram.setData(tightBuffer); /* create an element for the queue */ DatagramQueueElement element = new DatagramQueueElement(); element.setPacket(datagram); element.setTimestamp(receiptTime); /* add the element to the queue and notify everyone there's work to do */ queue.put(element); if (log.isTraceEnabled()) { log.trace("Enqueued: " + element); } } catch (Exception e) { log.warn("Unable to read datagram", e); } } }