List of usage examples for java.net DatagramSocket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:net.sourceforge.vulcan.ant.receiver.UdpEventSource.java
protected DatagramSocket openSocket() { try {/*from ww w. j av a2s . c o m*/ final SocketAddress addr = new InetSocketAddress(listenAddress, port); final DatagramSocket socket = new DatagramSocket(addr); socket.setSoTimeout(timeout); this.port = socket.getLocalPort(); return socket; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:poisondog.net.udp.SendMission.java
public Void execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(); socket.setReuseAddress(true);//from w w w. ja v a2 s . c o m socket.setBroadcast(parameter.getBroadcast()); if (parameter.getTimeout() > 0) socket.setSoTimeout(parameter.getTimeout()); String data = IOUtils.toString(parameter.getInputStream()); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length()); packet.setAddress(InetAddress.getByName(parameter.getHost())); if (parameter.getPort() > 0) packet.setPort(parameter.getPort()); socket.send(packet); socket.close(); return null; }
From source file:poisondog.net.udp.DatagramMission.java
public DatagramResponse execute(DatagramParameter parameter) throws IOException { DatagramSocket socket = new DatagramSocket(null); socket.setReuseAddress(true);//from ww w .ja va2 s .com socket.setBroadcast(parameter.getBroadcast()); if (parameter.getTimeout() > 0) socket.setSoTimeout(parameter.getTimeout()); String data = IOUtils.toString(parameter.getInputStream()); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length()); packet.setAddress(InetAddress.getByName(parameter.getHost())); packet.setPort(parameter.getPort()); socket.send(packet); DatagramResponse response = new DatagramResponse(parameter.getResponseLength()); DatagramPacket responsePacket = new DatagramPacket(response.getContent(), response.getContent().length); socket.receive(responsePacket); response.setAddress(responsePacket.getAddress().getHostAddress()); response.setPacketLength(responsePacket.getLength()); socket.close(); return response; }
From source file:org.shept.util.Monitor.java
/** * Send a simple 'Keep Alive' Datagram to the receiver *///from w ww.ja v a2 s . c om public Boolean keepAlive() { try { InetAddress adr = InetAddress.getByName(hostname); byte[] data = sendMsg.getBytes(); DatagramSocket socket = new DatagramSocket(); DatagramPacket pack = new DatagramPacket(data, data.length, adr, hostPort); socket.setSoTimeout(msecsSendTimeout); socket.send(pack); socket.close(); return true; } catch (Exception ex) { return false; } }
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. * /* ww 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:com.webobjects.monitor.application.HostsPage.java
private boolean hostMeetsMinimumVersion(InetAddress anAddress) { byte[] versionRequest; try {//w ww . j a v a2s .c om versionRequest = ("womp://queryVersion").getBytes(CharEncoding.UTF_8); } catch (UnsupportedEncodingException uee) { versionRequest = ("womp://queryVersion").getBytes(); } DatagramPacket outgoingPacket = new DatagramPacket(versionRequest, versionRequest.length, anAddress, WOApplication.application().lifebeatDestinationPort()); byte[] mbuffer = new byte[1000]; DatagramPacket incomingPacket = new DatagramPacket(mbuffer, mbuffer.length); DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.send(outgoingPacket); incomingPacket.setLength(mbuffer.length); socket.setSoTimeout(2000); socket.receive(incomingPacket); String reply = new String(incomingPacket.getData()); if (reply.startsWith("womp://replyVersion/")) { int lastIndex = reply.lastIndexOf(":webObjects"); lastIndex += 11; String version = reply.substring(lastIndex); if (version.equals("4.5")) { return false; } } else { return false; } } catch (InterruptedIOException iioe) { return true; } catch (SocketException se) { return true; } catch (Throwable e) { return false; } finally { if (socket != null) { socket.close(); } } return true; }
From source file:com.esri.geoevent.test.performance.ClockSync.java
@Override public void run() { DatagramSocket socket = null; try {// w w w . ja v a 2s. c om byte[] incomingBuffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(incomingBuffer, incomingBuffer.length); ByteBuffer bb = ByteBuffer.allocate(8); DatagramPacket outgoingPacket = new DatagramPacket(bb.array(), 0, 8, null, port); socket = new DatagramSocket(port); socket.setSoTimeout(100); while (isRunning.get()) { try { socket.receive(packet); long now = System.currentTimeMillis(); bb.putLong(now); outgoingPacket.setAddress(packet.getAddress()); outgoingPacket.setPort(packet.getPort()); socket.send(outgoingPacket); bb.clear(); //System.out.println("Sent the time " + now); } catch (SocketTimeoutException ex) { // Do nothing if nothing was sent. } } } catch (BindException e) { // port is in use - increment and try again port++; this.run(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(socket); } }
From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java
/** * If receiving new datagrams fails with a {@link SocketException}, this * method is called to renew the socket - if possible. * //w w w. j a v a 2s .c o m * @param socketException * the exception that occurred. * @param failedSocket * the socket that caused the exception. By default, he socket * will be closed in order to be able to reopen it. * Implementations may also try to reuse the socket, in * dependence of the <code>socketException</code>. * @return the new socket or <code>null</code> if the listen thread should * be terminated with the provided exception. * @throws SocketException * a new socket exception if the socket could not be renewed. * @since 2.2.2 */ protected DatagramSocket renewSocketAfterException(SocketException socketException, DatagramSocket failedSocket) throws SocketException { if ((failedSocket != null) && (!failedSocket.isClosed())) { failedSocket.close(); } DatagramSocket s = new DatagramSocket(udpAddress.getPort(), udpAddress.getInetAddress()); s.setSoTimeout(socketTimeout); return s; }
From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java
private synchronized DatagramSocket ensureSocket() throws SocketException { DatagramSocket s = socket; if (s == null) { s = new DatagramSocket(udpAddress.getPort()); s.setSoTimeout(socketTimeout); this.socket = s; }/* w w w . j av a2 s . c om*/ return s; }
From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoDiscoveryService.java
public void sendWemoDiscoveryMessage() { logger.debug("wemoDiscovery() is called!"); try {/* w ww. j a va 2 s . c o m*/ InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT); // Request-Packet-Constructor StringBuffer discoveryMessage = new StringBuffer(); discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n"); discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n"); discoveryMessage.append("ST: upnp:rootdevice\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\r\n"); discoveryMessage.append("\r\n"); logger.trace("Request: {}", discoveryMessage.toString()); byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes(); DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress); // Send multi-cast packet MulticastSocket multicast = null; try { multicast = new MulticastSocket(null); multicast.bind(srcAddress); logger.trace("Source-Address = '{}'", srcAddress); multicast.setTimeToLive(4); logger.debug("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener DatagramSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { receivePacket = new DatagramPacket(new byte[1536], 1536); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); logger.trace("Received message: {}", message); new Thread(new Runnable() { @Override public void run() { String label = "WeMo Device"; String wemoUDN = null; String wemoLocation = null; String wemoFriendlyName = null; String wemoModelName = null; ThingUID uid = null; if (message != null) { if (message.contains("Socket-1_0") || message.contains("Insight-1_0") || message.contains("Motion-1_0") || message.contains("Lightswitch-1_0")) { wemoUDN = StringUtils.substringBetween(message, "USN: uuid:", "::upnp:rootdevice"); logger.debug("Wemo device with UDN '{}' found", wemoUDN); wemoLocation = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); if (wemoLocation != null) { try { int timeout = 5000; String response = HttpUtil.executeUrl("GET", wemoLocation + "/setup.xml", timeout); wemoFriendlyName = StringUtils.substringBetween(response, "<friendlyName>", "</friendlyName>"); logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName, wemoLocation); wemoModelName = StringUtils.substringBetween(response, "<modelName>", "</modelName>"); logger.trace("Wemo device '{}' has model name '{}'", wemoFriendlyName, wemoModelName); label = "Wemo" + wemoModelName; switch (wemoModelName) { case "Socket": logger.debug( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN); break; case "Insight": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN); break; case "LightSwitch": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN); break; case "Motion": logger.trace( "Creating ThingUID for device model '{}' with UDN '{}'", wemoModelName, wemoUDN); uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN); break; } Map<String, Object> properties = new HashMap<>(4); properties.put(UDN, wemoUDN); properties.put(LOCATION, wemoLocation); DiscoveryResult result = DiscoveryResultBuilder.create(uid) .withProperties(properties).withLabel(label).build(); thingDiscovered(result); } catch (Exception te) { logger.error("Could not discover WeMo device", te); } } } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not send Wemo device discovery", e); } }