List of usage examples for java.net DatagramSocket close
public void close()
From source file:com.mobilyzer.measurements.RRCTask.java
/** * Sends a bunch of UDP packets of the size indicated and wait for the response. * //from ww w . j a v a2s . c o m * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the * total time is the time for the first packet to leave until the last packet arrives. AFter 7000 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets * lost is recorded. * * @param serverAddr server to which to send the packets * @param size size of the packets * @param num number of packets to send * @param packetSize size of the packets sent * @param port port to send the packets to * @return first value: the amount of time to send all packets and get a response. second value: * number of packets lost, on a timeout. * @throws IOException */ public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port) throws IOException { long startTime = 0; long endTime = 0; byte[] buf = new byte[size]; byte[] rcvBuf = new byte[packetSize]; long[] retval = { -1, -1 }; long numLost = 0; int i = 0; DatagramSocket socket = new DatagramSocket(); DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length); DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port); try { socket.setSoTimeout(7000); startTime = System.currentTimeMillis(); Logger.d("Sending packet, waiting for response "); for (i = 0; i < num; i++) { socket.send(packet); } for (i = 0; i < num; i++) { socket.receive(packetRcv); if (i == 0) { endTime = System.currentTimeMillis(); } } } catch (SocketTimeoutException e) { Logger.d("Timed out"); numLost += (num - i); socket.close(); } Logger.d("Sending complete: " + endTime); retval[0] = endTime - startTime; retval[1] = numLost; return retval; }
From source file:com.mobiperf.measurements.RRCTask.java
/** * Sends a bunch of UDP packets of the size indicated and wait for the response. * // w w w . j av a2 s . co m * Counts how long it takes for all the packets to return. PAckets are currently not labelled: the * total time is the time for the first packet to leave until the last packet arrives. AFter 7000 * ms it is assumed packets are lost and the socket times out. In that case, the number of packets * lost is recorded. * * @param serverAddr server to which to send the packets * @param size size of the packets * @param num number of packets to send * @param packetSize size of the packets sent * @param port port to send the packets to * @return first value: the amount of time to send all packets and get a response. second value: * number of packets lost, on a timeout. * @throws IOException */ public static long[] sendMultiPackets(InetAddress serverAddr, int size, int num, int packetSize, int port) throws IOException { long startTime = 0; long endTime = 0; byte[] buf = new byte[size]; byte[] rcvBuf = new byte[packetSize]; long[] retval = { -1, -1 }; long numLost = 0; int i = 0; long dataConsumedThisTask = 0; DatagramSocket socket = new DatagramSocket(); DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length); DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port); // number * (packet sent + packet received) dataConsumedThisTask += num * (size + packetSize); try { socket.setSoTimeout(7000); startTime = System.currentTimeMillis(); Logger.d("Sending packet, waiting for response "); for (i = 0; i < num; i++) { socket.send(packet); } for (i = 0; i < num; i++) { socket.receive(packetRcv); if (i == 0) { endTime = System.currentTimeMillis(); } } } catch (SocketTimeoutException e) { Logger.d("Timed out"); numLost += (num - i); socket.close(); } Logger.d("Sending complete: " + endTime); retval[0] = endTime - startTime; retval[1] = numLost; incrementData(dataConsumedThisTask); return retval; }
From source file:us.nineworlds.serenity.core.services.GDMService.java
@Override protected void onHandleIntent(Intent intent) { try {//from ww w . j a v a 2 s . c om 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:com.clustercontrol.agent.Agent.java
/** * ??awakeAgent?//from w ww . java2s . co m * 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:com.t_oster.visicut.misc.Helper.java
public static List<String> findVisiCamInstances() { List<String> result = new LinkedList<String>(); // Find the server using UDP broadcast try {//ww w . j av a 2 s . c om //Open a random port to send the package DatagramSocket c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "VisiCamDiscover".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); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> 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) { } } } //Wait for a response byte[] recvBuf = new byte[15000]; c.setSoTimeout(3000); while (true) { DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); try { c.receive(receivePacket); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); //Close the port! c.close(); if (message.startsWith("http")) { result.add(message); } } catch (SocketTimeoutException e) { break; } } } catch (IOException ex) { } return result; }
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. * // www . j av a 2 s. co m * @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:uk.me.sa.lightswitch.android.net.RequestMessage.java
private void sendMessageTo(byte[] message, String node) throws RemoteMessageException { try {//ww w . j av a 2 s . co m DatagramSocket s = new DatagramSocket(); try { InetAddress[] addresses = InetAddress.getAllByName(node); List<IOException> failed = new ArrayList<IOException>(addresses.length); for (InetAddress address : addresses) { log.trace("Sending {} bytes to {}", message.length, address); try { s.send(new DatagramPacket(message, message.length, new InetSocketAddress(address, SERVICE))); } catch (IOException e) { log.warn("Error sending datagram packet", e); failed.add(e); } } if (addresses.length == 0) { log.error("No hosts to send to"); throw new RemoteMessageException(new IllegalArgumentException("No hosts to send to")); } else if (failed.size() == addresses.length) { log.error("Error sending all datagram packets"); throw new RemoteMessageException(failed.get(0)); } else if (!failed.isEmpty()) { log.error("Error sending some (but not all) datagram packets"); } } catch (UnknownHostException e) { log.error("Error resolving hostname", e); throw new RemoteMessageException(e); } catch (RuntimeException e) { log.error("Error sending request message", e); throw new RemoteMessageException(e); } finally { s.close(); } } catch (SocketException e) { log.error("Error creating socket", e); throw new RemoteMessageException(e); } }
From source file:org.openhab.binding.edimax.internal.UDPDiscoverer.java
private EdimaxDevice[] discover() throws SocketException, UnknownHostException, IOException { List<EdimaxDevice> discoveredDevices = new ArrayList<EdimaxDevice>(); DatagramSocket serverSocket = null; try {/*w w w . ja v a2s . c om*/ serverSocket = new DatagramSocket(12346); // choose random port, // because with empty // port sometimes error // occures. // send UDP broadcast InetAddress ipAddress = InetAddress.getByName("255.255.255.255"); byte[] sendData = DISCOVERY_BYTES; DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 20560); serverSocket.send(sendPacket); // receive serverSocket.setSoTimeout(1000 * 5); byte[] receiveData = new byte[1024]; try { while (true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData()); if (!StringUtils.isEmpty(sentence) && sentence.contains("EDIMAX")) { byte[] mac = new byte[6]; System.arraycopy(receivePacket.getData(), 0, mac, 0, 6); String encodedMAC = Hex.encodeHexString(mac).toUpperCase(); InetAddress discoveredIp = receivePacket.getAddress(); EdimaxDevice dev = new EdimaxDevice(); dev.setIp(discoveredIp.getHostAddress()); dev.setMac(encodedMAC); discoveredDevices.add(dev); } } } catch (SocketTimeoutException e) { // intended to happen } } finally { if (serverSocket != null) { serverSocket.close(); } } return discoveredDevices.toArray(new EdimaxDevice[discoveredDevices.size()]); }
From source file:org.apache.jmeter.JMeter.java
private static void waitForSignals(final List<JMeterEngine> engines, DatagramSocket socket) { byte[] buf = new byte[80]; System.out.println(//from w w w. j a v a 2 s . c o m "Waiting for possible Shutdown/StopTestNow/Heapdump message on port " + socket.getLocalPort()); DatagramPacket request = new DatagramPacket(buf, buf.length); try { while (true) { socket.receive(request); InetAddress address = request.getAddress(); // Only accept commands from the local host if (address.isLoopbackAddress()) { String command = new String(request.getData(), request.getOffset(), request.getLength(), "ASCII"); System.out.println("Command: " + command + " received from " + address); log.info("Command: " + command + " received from " + address); if (command.equals("StopTestNow")) { for (JMeterEngine engine : engines) { engine.stopTest(true); } } else if (command.equals("Shutdown")) { for (JMeterEngine engine : engines) { engine.stopTest(false); } } else if (command.equals("HeapDump")) { HeapDumper.dumpHeap(); } else { System.out.println("Command: " + command + " not recognised "); } } } } catch (Exception e) { System.out.println(e); } finally { socket.close(); } }
From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java
/** * Tests turning on the UDPCommunication while it is off. * /*w ww.j a v a 2s . co 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); }