List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Creates a new task manager address request packet. * //from w w w . ja v a 2s . com * @param magicNumber * the magic number to identify this discovery service * @return a new task manager address request packet */ private static DatagramPacket createTaskManagerAddressRequestPacket(final int magicNumber) { final byte[] bytes = new byte[12]; integerToByteArray(magicNumber, MAGIC_NUMBER_OFFSET, bytes); integerToByteArray(generateRandomPacketID(), PACKET_ID_OFFSET, bytes); integerToByteArray(TM_ADDRESS_REQUEST_ID, PACKET_TYPE_ID_OFFSET, bytes); return new DatagramPacket(bytes, bytes.length); }
From source file:com.packetsender.android.PacketListenerService.java
@Override protected void onHandleIntent(Intent intent) { dataStore = new DataStorage(getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0), getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0), getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)); listenportTCP = dataStore.getTCPPort(); listenportUDP = dataStore.getUDPPort(); Log.i("service", DataStorage.FILE_LINE("TCP: " + listenportTCP + " / UDP: " + listenportUDP)); Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0); startNotification();//from www .jav a2s . c om CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); ByteBuffer response = null; try { response = encoder.encode(CharBuffer.wrap("response")); } catch (CharacterCodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { SocketAddress localportTCP = new InetSocketAddress(listenportTCP); SocketAddress localportUDP = new InetSocketAddress(listenportUDP); tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localportTCP); udpserver = DatagramChannel.open(); udpserver.socket().bind(localportUDP); tcpserver.configureBlocking(false); udpserver.configureBlocking(false); Selector selector = Selector.open(); tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); receiveBuffer.clear(); shutdownListener = new Runnable() { public void run() { if (false) { try { tcpserver.close(); } catch (IOException e) { } try { udpserver.close(); } catch (IOException e) { } stopSelf(); } else { mHandler.postDelayed(shutdownListener, 2000); } } }; sendListener = new Runnable() { public void run() { //Packet fetchedPacket = mDbHelper.needSendPacket(); Packet[] fetchedPackets = dataStore.fetchAllServicePackets(); if (fetchedPackets.length > 0) { dataStore.clearServicePackets(); Log.d("service", DataStorage.FILE_LINE("sendListener found " + fetchedPackets.length + " packets")); for (int i = 0; i < fetchedPackets.length; i++) { Packet fetchedPacket = fetchedPackets[i]; Log.d("service", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString())); } new SendPacketsTask().execute(fetchedPackets); } mHandler.postDelayed(sendListener, 2000); } }; //start shutdown listener mHandler.postDelayed(shutdownListener, 2000); //start send listener mHandler.postDelayed(sendListener, 5000); while (true) { try { // Handle per-connection problems below // Wait for a client to connect Log.d("service", DataStorage.FILE_LINE("waiting for connection")); selector.select(); Log.d("service", DataStorage.FILE_LINE("client connection")); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); Channel c = (Channel) key.channel(); if (key.isAcceptable() && c == tcpserver) { SocketChannel client = tcpserver.accept(); if (client != null) { Socket tcpSocket = client.socket(); packetCounter++; DataInputStream in = new DataInputStream(tcpSocket.getInputStream()); byte[] buffer = new byte[1024]; int received = in.read(buffer); byte[] bufferConvert = new byte[received]; System.arraycopy(buffer, 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = tcpSocket.getPort(); storepacket.port = tcpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("TCP:" + storepacket.toAscii(), "From " + storepacket.fromIP); Log.i("service", DataStorage.FILE_LINE("Got TCP")); //dataStore.SavePacket(storepacket); /* Intent tcpIntent = new Intent(); tcpIntent.setAction(ResponseReceiver.ACTION_RESP); tcpIntent.addCategory(Intent.CATEGORY_DEFAULT); tcpIntent.putExtra(PARAM_OUT_MSG, storepacket.name); sendBroadcast(tcpIntent); */ storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false) //mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "TCP"; storepacket.fromIP = "You"; storepacket.toIP = tcpSocket.getInetAddress().getHostAddress(); storepacket.fromPort = tcpSocket.getLocalPort(); storepacket.port = tcpSocket.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); client.write(response); // send response } client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { DatagramSocket udpSocket; DatagramPacket udpPacket; byte[] buffer = new byte[2048]; // Create a packet to receive data into the buffer udpPacket = new DatagramPacket(buffer, buffer.length); udpSocket = udpserver.socket(); receiveBuffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) udpserver.receive(receiveBuffer); if (clientAddress != null) { String fromAddress = clientAddress.getAddress().getHostAddress(); packetCounter++; int received = receiveBuffer.position(); byte[] bufferConvert = new byte[received]; System.arraycopy(receiveBuffer.array(), 0, bufferConvert, 0, bufferConvert.length); Packet storepacket = new Packet(); storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = clientAddress.getAddress().getHostAddress(); storepacket.toIP = "You"; storepacket.fromPort = clientAddress.getPort(); storepacket.port = udpSocket.getLocalPort(); storepacket.data = bufferConvert; UpdateNotification("UDP:" + storepacket.toAscii(), "From " + storepacket.fromIP); //dataStore.SavePacket(storepacket); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); if (false)//mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSE).trim().equalsIgnoreCase("Yes")) { storepacket = new Packet(); storepacket.name = dataStore.currentTimeStamp(); ; storepacket.tcpOrUdp = "UDP"; storepacket.fromIP = "You"; storepacket.toIP = clientAddress.getAddress().getHostAddress(); storepacket.fromPort = udpSocket.getLocalPort(); storepacket.port = clientAddress.getPort(); // storepacket.data = Packet.toBytes(mDbHelper.getSettings(PSDbAdapter.KEY_SETTINGS_SENDRESPONSETEXT)); //dataStore.SavePacket(storepacket); udpserver.send(response, clientAddress); storepacket.nowMe(); dataStore.saveTrafficPacket(storepacket); Log.d("service", DataStorage.FILE_LINE("sendBroadcast")); } } } } } catch (java.io.IOException e) { Log.i("service", DataStorage.FILE_LINE("IOException ")); } catch (Exception e) { Log.w("service", DataStorage.FILE_LINE("Fatal Error: " + Log.getStackTraceString(e))); } } } catch (BindException e) { //mDbHelper.putServiceError("Error binding to port"); dataStore.putToast("Port already in use."); Log.w("service", DataStorage.FILE_LINE("Bind Exception: " + Log.getStackTraceString(e))); } catch (Exception e) { //mDbHelper.putServiceError("Fatal Error starting service"); Log.w("service", DataStorage.FILE_LINE("Startup error: " + Log.getStackTraceString(e))); } stopNotification(); }
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); // /* w w w . j a va2 s. co m*/ try { mReceviedSocket.receive(packet); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return packet.getData(); }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Creates a new task manager address reply packet. * //from w w w .j a va2 s . c o m * @param taskManagerAddress * the address of the task manager which sent the request * @param magicNumber * the magic number to identify this discovery service * @return a new task manager address reply packet */ private static DatagramPacket createTaskManagerAddressReplyPacket(final InetAddress taskManagerAddress, final int magicNumber) { final byte[] addr = taskManagerAddress.getAddress(); final byte[] bytes = new byte[20 + addr.length]; integerToByteArray(magicNumber, MAGIC_NUMBER_OFFSET, bytes); integerToByteArray(generateRandomPacketID(), PACKET_ID_OFFSET, bytes); integerToByteArray(TM_ADDRESS_REPLY_ID, PACKET_TYPE_ID_OFFSET, bytes); integerToByteArray(addr.length, PAYLOAD_OFFSET, bytes); System.arraycopy(addr, 0, bytes, PAYLOAD_OFFSET + 4, addr.length); return new DatagramPacket(bytes, bytes.length); }
From source file:UDPInputStream.java
/****************** receiving more data ******************/ /*//w w w .jav a 2 s . c o m ***************************************************************** *** *** *** Name : receive *** *** By : U. Bergstrom (Creare Inc., Hanover, NH) *** *** For : E-Scan *** *** Date : October, 2001 *** *** *** *** Copyright 2001 Creare Inc. *** *** All Rights Reserved *** *** *** *** Description : *** *** A blocking read to receive more data from the UDP *** *** socket. *** *** *** ***************************************************************** */ private void receive() throws IOException { dpack = new DatagramPacket(ddata, PACKET_BUFFER_SIZE); dsock.receive(dpack); packIdx = 0; packSize = dpack.getLength(); }
From source file:Networking.Networking.java
/** * Receives data via UDP on {@see #udpSocket}. * @return {@code DatagramPacket} the packet received. *//*from w ww .j ava 2s .co m*/ 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:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the network address with which the task manager shall announce itself to the job manager. To determine * the address this method exchanges packets with the job manager. * /*from ww w. j a v a 2s.com*/ * @param jobManagerAddress * the address of the job manager * @return the address with which the task manager shall announce itself to the job manager * @throws DiscoveryException * thrown if an error occurs during the packet exchange */ public static InetAddress getTaskManagerAddress(final InetAddress jobManagerAddress) throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetAddress taskManagerAddress = null; DatagramSocket socket = null; try { socket = new DatagramSocket(); LOG.debug("Setting socket timeout to " + CLIENTSOCKETTIMEOUT); socket.setSoTimeout(CLIENTSOCKETTIMEOUT); final DatagramPacket responsePacket = new DatagramPacket(new byte[RESPONSE_PACKET_SIZE], RESPONSE_PACKET_SIZE); for (int retries = 0; retries < DISCOVERFAILURERETRIES; retries++) { final DatagramPacket addressRequest = createTaskManagerAddressRequestPacket(magicNumber); addressRequest.setAddress(jobManagerAddress); addressRequest.setPort(discoveryPort); LOG.debug("Sending Task Manager address request to " + addressRequest.getSocketAddress()); socket.send(addressRequest); try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.warn("Timeout wainting for task manager address reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.warn("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != TM_ADDRESS_REPLY_ID) { LOG.warn("Received response of unknown type " + packetTypeID + ", discarding..."); continue; } taskManagerAddress = extractInetAddress(responsePacket); break; } } catch (IOException ioe) { throw new DiscoveryException(StringUtils.stringifyException(ioe)); } finally { if (socket != null) { socket.close(); } } if (taskManagerAddress == null) { throw new DiscoveryException("Unable to obtain task manager address"); } return taskManagerAddress; }
From source file:net.dv8tion.jda.audio.AudioConnection.java
private void setupReceiveThread() { if (receiveHandler != null && udpSocket != null) { if (receiveThread == null) { receiveThread = new Thread("AudioConnection ReceiveThread Guild: " + channel.getGuild().getId()) { @Override//from w w w . j ava2 s .c om public void run() { try { udpSocket.setSoTimeout(100); } 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()); String userId = ssrcMap.get(decryptedPacket.getSSRC()); Decoder decoder = opusDecoders.get(decryptedPacket.getSSRC()); if (userId == null) { byte[] audio = decryptedPacket.getEncodedAudio(); if (!Arrays.equals(audio, silenceBytes)) LOG.debug("Received audio data with an unknown SSRC id."); } else if (decoder == null) LOG.warn( "Received audio data with known SSRC, but opus decoder for this SSRC was null. uh..HOW?!"); else if (!decoder.isInOrder(decryptedPacket.getSequence())) LOG.trace("Got out-of-order audio packet. Ignoring."); else { 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.restcomm.sbc.media.MediaZone.java
public DatagramPacket receiveRtcp() throws IOException { if (mediaZonePeer.rtcpSocket == null) { throw new IOException("NULL Socket on " + this.toPrint()); }//w w w .ja v a2 s .co m mediaZonePeer.rtcpSocket.receive(rdgram); if (rdgram == null || rdgram.getLength() < 8) { LOG.warn("RTCPPacket too short, not sending [" + (rdgram != null ? rdgram.getLength() : "NULL") + "]"); rdgram = new DatagramPacket(rbuffer, BUFFER); return null; } //LOG.trace("<---RTCP("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+(proxyPort+1)+"/"+rdgram.getAddress()+":"+rdgram.getPort()+"["+rdgram.getLength()+"]"); //LOG.trace("<---RTCP via socket "+toPrint(mediaZonePeer.rtcpSocket)); return rdgram; }
From source file:com.all.landownloader.discovery.LanDiscoverySocket.java
public LanDiscoveredPeer listen() throws IOException, IllegalArgumentException { MulticastSocket socket = new MulticastSocket(PORT); socket.joinGroup(addressGroup);/* w w w . j ava2 s. c o m*/ byte[] buf = new byte[BUF_LENGTH]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); socket.leaveGroup(addressGroup); socket.close(); InetAddress address = packet.getAddress(); byte[] remotePortBuffer = new byte[4]; System.arraycopy(buf, HEADER_LENGTH, remotePortBuffer, 0, remotePortBuffer.length); LanDiscoveredPeer discoveredPeer = new LanDiscoveredPeer(address, LanUtils.decodeInt(remotePortBuffer)); if (eq(BYE_MSG, buf, HEADER_LENGTH)) { addresses.remove(address); RegisteredAddress remove = quickLeases.remove(address); if (remove != null) { leases.remove(remove); } return null; } RegisteredAddress reg = quickLeases.get(discoveredPeer); long nextLeaseTime = System.currentTimeMillis() + this.leaseTime; if (reg == null) { reg = new RegisteredAddress(nextLeaseTime, discoveredPeer); quickLeases.put(discoveredPeer, reg); } else { reg.setLease(nextLeaseTime); } if (eq(ANNOUNCE_MSG, buf, HEADER_LENGTH)) { reply(address); } leases.add(reg); addresses.add(discoveredPeer); return discoveredPeer; }