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:UDPTimeClient.java

public static void main(String[] args) throws Exception {

    DatagramChannel channel = DatagramChannel.open();
    // port 0 selects any available port
    SocketAddress address = new InetSocketAddress(0);
    DatagramSocket socket = channel.socket();
    socket.setSoTimeout(5000);
    socket.bind(address);/*ww w .j a va  2 s . c  o m*/

    SocketAddress server = new InetSocketAddress("time.nist.gov", 37);
    ByteBuffer buffer = ByteBuffer.allocate(8192);
    // time protocol always uses big-endian order
    buffer.order(ByteOrder.BIG_ENDIAN);
    // Must put at least one byte of data in the buffer;
    // it doesn't matter what it is.
    buffer.put((byte) 65);
    buffer.flip();

    channel.send(buffer, server);

    buffer.clear();
    buffer.put((byte) 0).put((byte) 0).put((byte) 0).put((byte) 0);
    channel.receive(buffer);
    buffer.flip();
    long secondsSince1970 = buffer.getLong();

    System.out.println(secondsSince1970);
    channel.close();

}

From source file:Main.java

public static void main(String args[]) {
    try {//from w ww  . j  a  v  a 2  s.  c  o  m

        InetAddress ia = InetAddress.getByName("www.java2s.com");

        DatagramSocket ds = new DatagramSocket();

        byte buffer[] = "hello".getBytes();
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length, ia, 80);
        ds.setSoTimeout(1000);
        ds.send(dp);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:DaytimeClient.java

public static void main(String args[]) throws java.io.IOException {
    // Figure out the host and port we're going to talk to
    String host = args[0];//  w  w  w . j  av  a  2s .c  om
    int port = 13;
    if (args.length > 1)
        port = Integer.parseInt(args[1]);

    // Create a socket to use
    DatagramSocket socket = new DatagramSocket();

    // Specify a 1-second timeout so that receive() does not block forever.
    socket.setSoTimeout(1000);

    // This buffer will hold the response. On overflow, extra bytes are
    // discarded: there is no possibility of a buffer overflow attack here.
    byte[] buffer = new byte[512];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(host, port));

    // Try three times before giving up
    for (int i = 0; i < 3; i++) {
        try {
            // Send an empty datagram to the specified host (and port)
            packet.setLength(0); // make the packet empty
            socket.send(packet); // send it out

            // Wait for a response (or timeout after 1 second)
            packet.setLength(buffer.length); // make room for the response
            socket.receive(packet); // wait for the response

            // Decode and print the response
            System.out.print(new String(buffer, 0, packet.getLength(), "US-ASCII"));
            // We were successful so break out of the retry loop
            break;
        } catch (SocketTimeoutException e) {
            // If the receive call timed out, print error and retry
            System.out.println("No response");
        }
    }

    // We're done with the channel now
    socket.close();
}

From source file:UdpEchoClient.java

public static void main(String[] args) {
    InetAddress address;//from   w ww . j av a2  s . co  m
    try {
        address = InetAddress.getByName(args[0]);
    } catch (UnknownHostException host) {
        System.out.println(host);
        return;
    }
    DatagramPacket pack = new DatagramPacket(testString.getBytes(), testString.length(), address, 7);
    DatagramPacket incoming = new DatagramPacket(new byte[256], 256);
    DatagramSocket sock = null;
    try {
        Calendar start, end;
        sock = new DatagramSocket();
        start = Calendar.getInstance();
        sock.send(pack);
        sock.setSoTimeout(5000);
        sock.receive(incoming);
        end = Calendar.getInstance();
        String reply = new String(incoming.getData());
        reply = reply.substring(0, testString.length());
        if (reply.equals(testString)) {
            System.out.println("Success");
            System.out.println("Time = " + (end.getTime().getTime() - start.getTime().getTime()) + "mS");
        } else
            System.out.println("Reply data did not match");
    } catch (SocketException socke) {
        System.out.println(socke);
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        sock.close();
    }
}

From source file:energy.usef.core.util.DateTimeUtil.java

private static synchronized String getUDPInfo(String message) {
    try {// w w  w . j av a 2  s. com
        LOGGER.debug("SENDING: {}", message);
        byte[] buf = message.getBytes();
        InetAddress address = InetAddress.getByName(serverIp);
        DatagramSocket socket = new DatagramSocket();
        socket.send(new DatagramPacket(buf, buf.length, address, port));
        DatagramPacket result = new DatagramPacket(new byte[PACKAGE_BUFFER], PACKAGE_BUFFER);
        socket.disconnect();
        socket.setSoTimeout(RESPONSE_TIMEOUT);
        socket.receive(result);
        socket.disconnect();
        socket.close();
        String resultStr = new String(result.getData()).trim();
        LOGGER.debug("RECEIVED: {} ", resultStr);
        errorCount = 0;
        return resultStr;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        errorCount++;
        if (errorCount >= MAX_ERROR_COUNT) {
            LOGGER.error("Unable to run simulation correctly.");
            System.exit(1);
        }
    }
    return null;
}

From source file:gravity.android.discovery.DiscoveryClient.java

public static ArrayList<DiscoveryServerInfo> findServer(WifiManager mWifi, int port, String token) {
    ArrayList<DiscoveryServerInfo> ret = new ArrayList<DiscoveryServerInfo>();

    try {/*w ww.  j av  a  2  s  . c o m*/
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.setBroadcast(true);
        InetAddress IPAddress = Utils.getBroadcastAddress(mWifi);
        Log.v("DISCOVERY_CLIENT", "broadcast addr " + IPAddress.getHostAddress());
        byte[] receiveData = new byte[2048];
        byte[] sendData = new byte[128];

        sendData = token.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        Log.v("DISCOVERY_CLIENT", "sent " + token);
        clientSocket.send(sendPacket);

        long t1 = System.currentTimeMillis();
        while (System.currentTimeMillis() - t1 <= 4000) // 4 secondi
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            try {
                clientSocket.setSoTimeout(500);
                clientSocket.receive(receivePacket);

                if (receivePacket.getAddress() != null && receivePacket.getAddress().getHostAddress() != null) {
                    String discovered_name, discovered_ip;
                    int discovered_port;

                    String received = new String(receivePacket.getData());

                    if (received != null) {
                        received = received.trim().substring(0, receivePacket.getLength()).trim();
                        Log.d("Recieved Msg Packet:", received);

                        //StringTokenizer st = new StringTokenizer(received, ",");

                        //Gravity Code
                        JSONObject recievedJson = new JSONObject(received);

                        try {
                            //discovered_name = st.nextToken();   
                            discovered_name = recievedJson.getString("name"); //Gravity code

                            discovered_ip = receivePacket.getAddress().getHostAddress();

                            //discovered_port = Integer.parseInt(st.nextToken());
                            discovered_port = recievedJson.getInt("port_to_share"); //Gravity code

                            Log.v("DISCOVERY_CLIENT", "discovered " + discovered_name + ", " + discovered_ip
                                    + ":" + discovered_port);

                            boolean add = true;
                            if (ret.size() > 0) {
                                for (DiscoveryServerInfo dsi : ret) {
                                    if (dsi != null && dsi.ip.equals(discovered_ip)) {
                                        add = false;
                                        break;
                                    }
                                }
                            }

                            if (add) {
                                ret.add(new DiscoveryServerInfo(discovered_name, discovered_ip,
                                        discovered_port));
                            }
                        } catch (NoSuchElementException nsee) {
                            Log.v("DISCOVERY_CLIENT", nsee.getLocalizedMessage());
                        }

                    }
                }

            } catch (SocketTimeoutException tex) {
                /* ignored */ }
        }

        clientSocket.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.e("DISCOVERY_CLIENT", ex.toString());
    }

    return ret;
}

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   www .j a va2s  . 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:org.hyperic.util.ntp.NtpClient.java

public NtpResponse getResponse() throws SocketException, UnknownHostException, IOException {
    DatagramSocket socket = new DatagramSocket();
    socket.setSoTimeout(this.timeout);

    InetAddress address = InetAddress.getByName(this.hostname);
    byte[] data = NtpResponse.getRequestBytes();
    DatagramPacket packet = new DatagramPacket(data, data.length, address, this.port);
    socket.send(packet);// ww  w. jav  a2 s. c om

    packet = new DatagramPacket(data, data.length);
    socket.receive(packet);

    NtpResponse response = NtpResponse.decodeResponse(now(), packet.getData());
    return response;
}

From source file:com.kecso.socket.ServerSocketControl.java

@Override
public void run() {
    DatagramSocket sock = null;

    try {//from   w w w .j  a v  a  2s  .  c  o m
        sock = new DatagramSocket(8888);
        sock.setSoTimeout(1000);

        byte[] buffer = new byte[65536];
        DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

        while (!Thread.currentThread().isInterrupted()) {
            try {
                sock.receive(incoming);
                byte[] data = incoming.getData();
                this.udpMessage = SerializationUtils.deserialize(data);

                byte[] response = SerializationUtils.serialize(
                        this.output != null
                                ? new UdpResponse((float) output.getSpeed(), (float) output.getVerticalSpeed(),
                                        (float) output.getAltitude(), (float) output.getRpm())
                                : null);
                DatagramPacket dp = new DatagramPacket(response, response.length, incoming.getAddress(),
                        incoming.getPort());
                sock.send(dp);
            } catch (SocketTimeoutException e) {
            }
        }
    } catch (Exception e) {
        System.err.println("IOException " + e);
    } finally {
        if (sock != null) {
            sock.close();
        }

    }
}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSender.java

private DatagramSocket createSocket(String host, int port, int timeout, int sendBufferSize) {
    try {//from w w  w.  j  a  v  a  2 s. c  o m
        final DatagramSocket datagramSocket = new DatagramSocket();

        datagramSocket.setSoTimeout(timeout);
        datagramSocket.setSendBufferSize(sendBufferSize);
        if (logger.isInfoEnabled()) {
            final int checkSendBufferSize = datagramSocket.getSendBufferSize();
            if (sendBufferSize != checkSendBufferSize) {
                logger.info("DatagramSocket.setSendBufferSize() error. {}!={}", sendBufferSize,
                        checkSendBufferSize);
            }
        }

        final InetSocketAddress serverAddress = new InetSocketAddress(host, port);
        datagramSocket.connect(serverAddress);
        return datagramSocket;
    } catch (SocketException e) {
        throw new IllegalStateException("DatagramSocket create fail. Cause" + e.getMessage(), e);
    }
}