List of usage examples for java.net DatagramPacket DatagramPacket
public DatagramPacket(byte buf[], int length)
From source file:net.pms.network.UPNPHelper.java
/** * Starts up two threads: one to broadcast UPnP ALIVE messages and another * to listen for responses. /* w ww.j a va 2 s .co m*/ * * @throws IOException Signals that an I/O exception has occurred. */ public static void listen() throws IOException { Runnable rAlive = new Runnable() { @Override public void run() { int delay = 10000; while (true) { sleep(delay); sendAlive(); // The first delay for sending an ALIVE message is 10 seconds, // the second delay is for 20 seconds. From then on, all other // delays are for 180 seconds. switch (delay) { case 10000: delay = 20000; break; case 20000: delay = 180000; break; } } } }; aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender"); aliveThread.start(); Runnable r = new Runnable() { @Override public void run() { boolean bindErrorReported = false; while (true) { MulticastSocket multicastSocket = null; try { // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166 multicastSocket = new MulticastSocket(configuration.getUpnpPort()); if (bindErrorReported) { logger.warn( "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!"); } NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName(); try { // Setting the network interface will throw a SocketException on Mac OSX // with Java 1.6.0_45 or higher, but if we don't do it some Windows // configurations will not listen at all. if (ni != null) { multicastSocket.setNetworkInterface(ni); } else if (PMS.get().getServer().getNetworkInterface() != null) { multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface()); logger.trace("Setting multicast network interface: " + PMS.get().getServer().getNetworkInterface()); } } catch (SocketException e) { // Not setting the network interface will work just fine on Mac OSX. } multicastSocket.setTimeToLive(4); multicastSocket.setReuseAddress(true); InetAddress upnpAddress = getUPNPAddress(); multicastSocket.joinGroup(upnpAddress); while (true) { byte[] buf = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buf, buf.length); multicastSocket.receive(receivePacket); String s = new String(receivePacket.getData()); InetAddress address = receivePacket.getAddress(); if (s.startsWith("M-SEARCH")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); if (configuration.getIpFiltering().allowed(address)) { logger.trace( "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]"); if (StringUtils.indexOf(s, "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:service:ContentDirectory:1"); } if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) { sendDiscover(remoteAddr, remotePort, "upnp:rootdevice"); } if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, "ssdp:all") > 0) { sendDiscover(remoteAddr, remotePort, "urn:schemas-upnp-org:device:MediaServer:1"); } if (StringUtils.indexOf(s, PMS.get().usn()) > 0) { sendDiscover(remoteAddr, remotePort, PMS.get().usn()); } } } else if (s.startsWith("NOTIFY")) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]"); } } } catch (BindException e) { if (!bindErrorReported) { logger.error("Unable to bind to " + configuration.getUpnpPort() + ", which means that PMS will not automatically appear on your renderer! " + "This usually means that another program occupies the port. Please " + "stop the other program and free up the port. " + "PMS will keep trying to bind to it...[" + e.getMessage() + "]"); } bindErrorReported = true; sleep(5000); } catch (IOException e) { logger.error("UPNP network exception", e); sleep(1000); } finally { if (multicastSocket != null) { // Clean up the multicast socket nicely try { InetAddress upnpAddress = getUPNPAddress(); multicastSocket.leaveGroup(upnpAddress); } catch (IOException e) { } multicastSocket.disconnect(); multicastSocket.close(); } } } } }; listenerThread = new Thread(r, "UPNPHelper"); listenerThread.start(); }
From source file:cai.flow.collector.Collector.java
/** * * @throws Throwable//from w w w.ja va 2 s . com */ public void reader_loop() throws Throwable { DatagramSocket socket; try { try { socket = new DatagramSocket(localPort, localHost); socket.setReceiveBufferSize(receiveBufferSize); } catch (IOException exc) { logger.fatal("Reader - socket create error: " + localHost + ":" + localPort); logger.debug(exc); throw exc; } while (true) { byte[] buf = new byte[2048];// DatagramPacket p = null; if (p == null) { p = new DatagramPacket(buf, buf.length); try { socket.receive(p); } catch (IOException exc) { logger.error("Reader - socket read error: " + exc.getMessage()); logger.debug(exc); put_to_queue(null);// notifyAll break; } } if (this.sampler.shouldDue()) { put_to_queue(p); } p = null; } } catch (Throwable e) { logger.error("Exception trying to abort collector"); put_to_queue(null); throw e; } }
From source file:org.restcomm.sbc.media.MediaZone.java
public DatagramPacket receive() throws IOException { if (mediaZonePeer.socket == null) { throw new IOException("NULL Socket on " + this.toPrint()); }//from ww w . j av a2s.com mediaZonePeer.socket.receive(dgram); if (dgram == null || dgram.getLength() < 8) { LOG.warn("RTPPacket too short on " + this.toPrint(mediaZonePeer.socket) + " not sending [" + (dgram != null ? dgram.getLength() : "NULL") + "]"); dgram = new DatagramPacket(buffer, BUFFER); return null; } //LOG.trace("<---("+this.mediaType+", "+this.direction+") LocalProxy "+proxyHost+":"+proxyPort+"/"+dgram.getAddress()+":"+dgram.getPort()+"["+dgram.getLength()+"]"); //LOG.trace("<--- via socket "+toPrint(mediaZonePeer.socket)); dgram.setData(mediaZonePeer.encodeRTP(dgram.getData(), 0, dgram.getLength())); logCounter++; if (logCounter == rtpCountLog) { RawPacket rtp = new RawPacket(dgram.getData(), 0, dgram.getLength()); LOG.trace("<---[PayloadType " + rtp.getPayloadType() + "](" + this.mediaType + ", " + this.direction + ") LocalProxy " + proxyHost + ":" + proxyPort + "/" + dgram.getAddress() + ":" + dgram.getPort() + "[" + dgram.getLength() + "]"); } packetsRecvCounter++; return dgram; }
From source file:net.anidb.udp.UdpConnection.java
/** * <p>Sends a request and receives a response from the server.</p> * <p>The session key will be set automatically, if the client is logged * in.</p>/*from w ww . j a v a2s . co m*/ * @param request The request. * @return The response. * @throws IllegalArgumentException If the request is <code>null</code>. * @throws UdpConnectionException If a connection problem occured. */ protected UdpResponse communicate(final UdpRequest request) throws UdpConnectionException { DatagramPacket packet; byte[] buffer; UdpResponse response; if (request == null) { throw new IllegalArgumentException("Argument request is null."); } synchronized (this.monitor) { if (this.socket == null) { throw new UdpConnectionException("Connection is already closed."); } if (this.sessionKey != null) { request.addParameter("s", this.sessionKey); } LOG.debug("send = [" + request.toString() + "]"); // Flood protection. this.doFloodProtection(); try { packet = request.createPacket(this.charset); } catch (UnsupportedEncodingException uee) { throw new UdpConnectionException("Couldn't encode the request.", uee); } try { // Remember timestamp for flood protection. this.timestampLastPacketSend = System.currentTimeMillis(); this.socket.send(packet); } catch (Throwable t) { throw new UdpConnectionException("Couldn't send request: " + t.getLocalizedMessage(), t); } // All packets should be smaller than 64k -> maximum MTU size. buffer = new byte[65536]; packet = new DatagramPacket(buffer, buffer.length); try { this.socket.receive(packet); } catch (Throwable t) { throw new UdpConnectionException("Couldn't receive reply: " + t.getLocalizedMessage(), t); } } try { response = UdpResponse.getInstance(packet, this.charset); } catch (UnsupportedEncodingException uee) { throw new UdpConnectionException("Couldn't decode the response.", uee); } this.checkState(response); return response; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Attempts to retrieve the job managers address in the network through an * IP broadcast. This method should be called by the task manager. * // w w w.jav a 2s. c o m * @return the socket address of the job manager in the network * @throws DiscoveryException * thrown if the job manager's socket address could not be * discovered */ public static InetSocketAddress getJobManagerAddress() throws DiscoveryException { final int magicNumber = GlobalConfiguration.getInteger(MAGICNUMBER_KEY, DEFAULT_MAGICNUMBER); final int discoveryPort = GlobalConfiguration.getInteger(DISCOVERYPORT_KEY, DEFAULT_DISCOVERYPORT); InetSocketAddress jobManagerAddress = null; DatagramSocket socket = null; try { final Set<InetAddress> targetAddresses = getBroadcastAddresses(); if (targetAddresses.isEmpty()) { throw new DiscoveryException("Could not find any broadcast addresses available to this host"); } 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 lookupRequest = createJobManagerLookupRequestPacket(magicNumber); for (InetAddress broadcast : targetAddresses) { lookupRequest.setAddress(broadcast); lookupRequest.setPort(discoveryPort); LOG.debug("Sending discovery request to " + lookupRequest.getSocketAddress()); socket.send(lookupRequest); } try { socket.receive(responsePacket); } catch (SocketTimeoutException ste) { LOG.debug("Timeout wainting for discovery reply. Retrying..."); continue; } if (!isPacketForUs(responsePacket, magicNumber)) { LOG.debug("Received packet which is not destined to this Nephele setup"); continue; } final int packetTypeID = getPacketTypeID(responsePacket); if (packetTypeID != JM_LOOKUP_REPLY_ID) { LOG.debug("Received unexpected packet type " + packetTypeID + ", discarding... "); continue; } final int ipcPort = extractIpcPort(responsePacket); // Replace port from discovery service with the actual RPC port // of the job manager if (USE_IPV6) { // TODO: No connection possible unless we remove the scope identifier if (responsePacket.getAddress() instanceof Inet6Address) { try { jobManagerAddress = new InetSocketAddress( InetAddress.getByAddress(responsePacket.getAddress().getAddress()), ipcPort); } catch (UnknownHostException e) { throw new DiscoveryException(StringUtils.stringifyException(e)); } } else { throw new DiscoveryException(responsePacket.getAddress() + " is not a valid IPv6 address"); } } else { jobManagerAddress = new InetSocketAddress(responsePacket.getAddress(), ipcPort); } LOG.debug("Discovered job manager at " + jobManagerAddress); break; } } catch (IOException ioe) { throw new DiscoveryException(ioe.toString()); } finally { if (socket != null) { socket.close(); } } if (jobManagerAddress == null) { LOG.debug("Unable to discover Jobmanager via IP broadcast"); throw new DiscoveryException("Unable to discover JobManager via IP broadcast!"); } return jobManagerAddress; }
From source file:org.zxg.network.dhtcrawler.Crawler.java
@Override protected void sendUdp(UdpMsg msg) throws IOException { DatagramPacket datagramPacket = new DatagramPacket(msg.data, msg.data.length); datagramPacket.setSocketAddress(new InetSocketAddress(msg.addr.ip, msg.addr.port)); socket.send(datagramPacket);//from www .j a v a2s. com }
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);/* w w w.java2 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.echocat.jomon.net.dns.DnsServer.java
public void serveUDP(InetSocketAddress address) { try {/* w ww. j a v a 2 s. co m*/ final DatagramSocket sock = new DatagramSocket(address.getPort(), address.getAddress()); synchronized (_closeables) { _closeables.add(sock); } final short udpLength = 512; final byte[] in = new byte[udpLength]; final DatagramPacket indp = new DatagramPacket(in, in.length); DatagramPacket outdp = null; while (!currentThread().isInterrupted()) { indp.setLength(in.length); receive(sock, indp); final Message query; byte[] response; try { query = new Message(in); response = generateReply(query, in, indp.getLength(), null); if (response == null) { continue; } } catch (final IOException ignored) { response = formerrMessage(in); } if (outdp == null) { outdp = new DatagramPacket(response, response.length, indp.getAddress(), indp.getPort()); } else { outdp.setData(response); outdp.setLength(response.length); outdp.setAddress(indp.getAddress()); outdp.setPort(indp.getPort()); } sock.send(outdp); } } catch (final InterruptedIOException ignored) { currentThread().interrupt(); } catch (final IOException e) { LOG.warn("serveUDP(" + addrport(address.getAddress(), address.getPort()) + ")", e); } }
From source file:Reflector.java
private void listen(DatagramSocket ds) { // loop forever listening to packets, when they // arrive log them and notify all interested threads. byte[] buffer; DatagramPacket packet;//w w w . jav a 2 s. co m while (true) { try { buffer = new byte[MAX_PACKET_SIZE]; packet = new DatagramPacket(buffer, buffer.length); ds.receive(packet); logger.log("Packet received, " + packet.getLength() + " bytes"); eventNotify(packet); } catch (IOException e) { System.err.println("Error receiving packet\n"); e.printStackTrace(); } } }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Server side implementation of Discovery Service. *///from w w w .ja va2 s .c o m @Override public void run() { final DatagramPacket requestPacket = new DatagramPacket(new byte[64], 64); final Map<Integer, Long> packetIDMap = new HashMap<Integer, Long>(); while (this.isRunning) { try { this.serverSocket.receive(requestPacket); if (!isPacketForUs(requestPacket, this.magicNumber)) { LOG.debug("Received request packet which is not destined to this Nephele setup"); continue; } final Integer packetID = Integer.valueOf(extractPacketID(requestPacket)); if (packetIDMap.containsKey(packetID)) { LOG.debug("Request with ID " + packetID.intValue() + " already answered, discarding..."); continue; } else { final long currentTime = System.currentTimeMillis(); // Remove old entries final Iterator<Map.Entry<Integer, Long>> it = packetIDMap.entrySet().iterator(); while (it.hasNext()) { final Map.Entry<Integer, Long> entry = it.next(); if ((entry.getValue().longValue() + 5000L) < currentTime) { it.remove(); } } packetIDMap.put(packetID, Long.valueOf(currentTime)); } final int packetTypeID = getPacketTypeID(requestPacket); if (packetTypeID == JM_LOOKUP_REQUEST_ID) { LOG.debug("Received job manager lookup request from " + requestPacket.getSocketAddress()); final DatagramPacket responsePacket = createJobManagerLookupReplyPacket(this.ipcPort, this.magicNumber); responsePacket.setAddress(requestPacket.getAddress()); responsePacket.setPort(requestPacket.getPort()); this.serverSocket.send(responsePacket); } else if (packetTypeID == TM_ADDRESS_REQUEST_ID) { LOG.debug("Received task manager address request from " + requestPacket.getSocketAddress()); final DatagramPacket responsePacket = createTaskManagerAddressReplyPacket( requestPacket.getAddress(), this.magicNumber); responsePacket.setAddress(requestPacket.getAddress()); responsePacket.setPort(requestPacket.getPort()); this.serverSocket.send(responsePacket); } else { LOG.debug("Received packet of unknown type " + packetTypeID + ", discarding..."); } } catch (SocketTimeoutException ste) { LOG.debug("Discovery service: socket timeout"); } catch (IOException ioe) { if (this.isRunning) { // Ignore exception when service has been stopped LOG.error("Discovery service stopped working with IOException:\n" + ioe.toString()); } break; } } // Close the socket finally this.serverSocket.close(); }