Example usage for java.net DatagramSocket setSoTimeout

List of usage examples for java.net DatagramSocket setSoTimeout

Introduction

In this page you can find the example usage for java.net DatagramSocket setSoTimeout.

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

Usage

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 {/*from  w  w  w . j a va 2s  .co  m*/
        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:us.nineworlds.serenity.core.services.GDMService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/* w ww. j  a v  a 2 s  . com*/
        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.mobiperf.measurements.RRCTask.java

/** 
 * Send a single packet of the size indicated and wait for a response.
 * /*from w  ww. java  2s. co  m*/
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];
    long dataConsumedThisTask = 0;

    DatagramSocket socket = new DatagramSocket();
    DatagramPacket packetRcv = new DatagramPacket(rcvBuf, rcvBuf.length);

    dataConsumedThisTask += (size + rcvSize);

    DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, port);

    try {
        socket.setSoTimeout(7000);
        startTime = System.currentTimeMillis();
        Logger.d("Sending packet, waiting for response ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);
    incrementData(dataConsumedThisTask);
    return endTime - startTime;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Send a single packet of the size indicated and wait for a response.
 * //from www.j a  va 2s.c o  m
 * After 7000 ms, time out and return a value of -1 (meaning no response). Otherwise, return the
 * time from when the packet was sent to when a response was returned by the echo server.
 * 
 * @param serverAddr Echo server to calculate round trip
 * @param size size of packet to send in bytes
 * @param rcvSize size of packets sent from the echo server
 * @param port where the echo server is listening
 * @return The round trip time for the packet
 * @throws IOException
 */
public static long sendPacket(InetAddress serverAddr, int size, int rcvSize, int port) throws IOException {
    long startTime = 0;
    byte[] buf = new byte[size];
    byte[] rcvBuf = new byte[rcvSize];

    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 ");

        socket.send(packet);
        socket.receive(packetRcv);
    } catch (SocketTimeoutException e) {
        Logger.d("Timed out, trying again");
        socket.close();
        return -1;
    }
    long endTime = System.currentTimeMillis();
    Logger.d("Sending complete: " + endTime);

    return endTime - startTime;
}

From source file:com.mobilyzer.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * //from   w  w w  . j ava2s .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:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * /*from   w  w w.  j  a v a 2 s  .  c  om*/
 *  
 */
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:com.mobiperf.measurements.RRCTask.java

/**
 * Sends a bunch of UDP packets of the size indicated and wait for the response.
 * //from w  w w. jav a  2  s  .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;
    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: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 {/*  w  w w  .  j ava 2 s .  c o m*/
        //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:snapshotTools.java

private String callOvnmanager(String node, String action) {
    String result = "";
    DatagramSocket socket = null;
    int serverPort = 9999;
    DatagramPacket packet2Send;//from w w  w .j a va2  s  . c o  m
    DatagramPacket receivedPacket;
    InetAddress theServerAddress;
    byte[] outBuffer;
    byte[] inBuffer;
    inBuffer = new byte[8192];
    outBuffer = new byte[8192];
    try {
        HttpSession session = RuntimeAccess.getInstance().getSession();
        String sessionUser = (String) session.getAttribute("User");
        if (sessionUser == null) {
            sessionUser = "administrator";
        }
        JSONObject joCmd = new JSONObject();
        JSONObject joAction = new JSONObject(action);
        joCmd.put("sender", sessionUser);
        joCmd.put("target", "SNAPSHOT");
        joCmd.put("node", node);
        joCmd.put("action", joAction);
        String output = joCmd.toString();

        socket = new DatagramSocket();
        String actionName = joAction.get("name").toString();
        if (actionName.equals("create")) {
            socket.setSoTimeout(180000);
        } else {
            socket.setSoTimeout(60000);
        }

        InetAddress serverInet = InetAddress.getByName("localhost");
        socket.connect(serverInet, serverPort);
        outBuffer = output.getBytes();
        packet2Send = new DatagramPacket(outBuffer, outBuffer.length, serverInet, serverPort);

        try {
            // send the data
            socket.send(packet2Send);
            receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
            socket.receive(receivedPacket);
            // the server response is...
            result = new String(receivedPacket.getData(), 0, receivedPacket.getLength());
            session.setAttribute("LastActive", System.currentTimeMillis());
        } catch (Exception excep) {
            String msg = excep.getMessage();
            //String msg = excep.toString();
            joCmd.remove("action");
            joAction.put("result", "Error:" + msg);
            joCmd.put("action", joAction);
            result = joCmd.toString();
        }
        socket.close();

    } catch (Exception e) {
        log(ERROR, "callOvnmanager", e);
        return e.toString();
    }
    return result;
}

From source file:org.mule.transport.udp.UdpSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ImmutableEndpoint ep = (ImmutableEndpoint) key;
    DatagramSocket socket;

    if (ep instanceof InboundEndpoint) {
        int port = ep.getEndpointURI().getPort();
        String host = ep.getEndpointURI().getHost();
        if (port > 0) {
            if ("null".equalsIgnoreCase(host)) {
                socket = createSocket(port);
            } else {
                socket = createSocket(port, InetAddress.getByName(host));
            }//from   ww w  .  j  a  v a2 s.c  om
        } else {
            socket = createSocket();
        }
    } else {
        //If this is a client socket create a default instance
        socket = createSocket();
    }

    UdpConnector connector = (UdpConnector) ep.getConnector();
    //There is some overhead in stting socket timeout and buffer size, so we're
    //careful here only to set if needed
    if (connector.getReceiveBufferSize() != Connector.INT_VALUE_NOT_SET
            && socket.getReceiveBufferSize() != connector.getReceiveBufferSize()) {
        socket.setReceiveBufferSize(connector.getReceiveBufferSize());
    }
    if (connector.getSendBufferSize() != Connector.INT_VALUE_NOT_SET
            && socket.getSendBufferSize() != connector.getSendBufferSize()) {
        socket.setSendBufferSize(connector.getSendBufferSize());
    }
    if (connector.getTimeout() != Connector.INT_VALUE_NOT_SET
            && socket.getSoTimeout() != connector.getTimeout()) {
        socket.setSoTimeout(connector.getTimeout());
    }
    socket.setBroadcast(connector.isBroadcast());
    return socket;
}