Example usage for java.net Socket setSoTimeout

List of usage examples for java.net Socket setSoTimeout

Introduction

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

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket client = new Socket("google.com", 80);
    client.setSoTimeout(1000);
    System.out.println(client.getSoTimeout());

    client.close();//  w w w .  j  av a 2  s .  c  om
}

From source file:Finger.java

public static void main(String[] arguments) throws Exception {
    StringTokenizer split = new StringTokenizer(arguments[0], "@");
    String user = split.nextToken();
    String host = split.nextToken();

    Socket digit = new Socket(host, 79);
    digit.setSoTimeout(20000);
    PrintStream out = new PrintStream(digit.getOutputStream());
    out.print(user + "\015\012");
    BufferedReader in = new BufferedReader(new InputStreamReader(digit.getInputStream()));
    boolean eof = false;
    while (!eof) {
        String line = in.readLine();
        if (line != null)
            System.out.println(line);
        else/*from   w  ww . j  a  v  a  2s . c  o m*/
            eof = true;
    }
    digit.close();
}

From source file:com.googlecode.shutdownlistener.ShutdownUtility.java

public static void main(String[] args) throws Exception {
    final ShutdownConfiguration config = ShutdownConfiguration.getInstance();

    final String command;
    if (args.length > 0) {
        command = args[0];/*  w  w w. j ava  2s  .  c  om*/
    } else {
        command = config.getStatusCommand();
    }

    System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command);

    final InetAddress hostAddress = InetAddress.getByName(config.getHost());
    final Socket shutdownConnection = new Socket(hostAddress, config.getPort());
    try {
        shutdownConnection.setSoTimeout(5000);
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(shutdownConnection.getInputStream()));
        final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream());
        try {
            writer.println(command);
            writer.flush();

            while (true) {
                final String line = reader.readLine();
                if (line == null) {
                    break;
                }

                System.out.println(line);
            }
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
        }
    } finally {
        try {
            shutdownConnection.close();
        } catch (IOException ioe) {
        }
    }

}

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {//from  w  w  w  .  j  ava2  s .  co m
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils.java

public static boolean checkIfRemoteEndpointAccessible(String host, int port) {
    try {/*w w  w.  ja v  a2s .  com*/
        Socket discover = new Socket();
        discover.setSoTimeout(1000);
        discover.connect(new InetSocketAddress(host, port), 1000);
        discover.close();
        return true;
    } catch (ConnectException cne) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + cne.getMessage());
        }
        return false;
    } catch (IOException ioe) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + ioe.getMessage());
        }
        return false;
    }
}

From source file:org.csource.fastdfs.ClientGlobal.java

/**
* construct Socket object/*from  ww  w . jav  a 2  s .  c o  m*/
* @param ip_addr ip address or hostname
* @param port port number
* @return connected Socket object
*/
public static Socket getSocket(String ip_addr, int port) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(new InetSocketAddress(ip_addr, port), ClientGlobal.g_connect_timeout);
    return sock;
}

From source file:org.csource.fastdfs.ClientGlobal.java

/**
* construct Socket object//from   www.j  a  va 2 s  . com
* @param addr InetSocketAddress object, including ip address and port
* @return connected Socket object
*/
public static Socket getSocket(InetSocketAddress addr) throws IOException {
    Socket sock = new Socket();
    sock.setSoTimeout(ClientGlobal.g_network_timeout);
    sock.connect(addr, ClientGlobal.g_connect_timeout);
    return sock;
}

From source file:org.apache.jcs.auxiliary.remote.server.RemoteCacheServerFactory.java

/**
 * Starts up the remote cache server on this JVM, and binds it to the registry on the given host
 * and port.// w  w  w.jav  a2  s  . co  m
 * A remote cache is either a local cache or a cluster cache
 * @param host
 * @param port
 * @param propFile
 * @throws IOException
 */
public static void startup(String host, int port, String propFile) throws IOException {
    if (remoteCacheServer != null) {
        throw new IllegalArgumentException("Server already started.");
    }

    synchronized (RemoteCacheServer.class) {
        if (remoteCacheServer != null) {
            return;
        }

        if (log.isInfoEnabled()) {
            log.info("ConfigFileName = [" + propFile + "]");
        }

        try {
            // TODO make configurable.
            // use this socket factory to add a timeout.
            RMISocketFactory.setSocketFactory(new RMISocketFactory() {
                public Socket createSocket(String host, int port) throws IOException {
                    Socket socket = new Socket(host, port);
                    socket.setSoTimeout(DEFAULT_RMI_SOCKET_FACTORY_TIMEOUT_MS);
                    socket.setSoLinger(false, 0);
                    return socket;
                }

                public ServerSocket createServerSocket(int port) throws IOException {
                    return new ServerSocket(port);
                }
            });
        } catch (Exception e) {
            log.error("Problem setting custom RMI Socket Factory.", e);
        }

        // TODO: make automatic
        RemoteCacheServerAttributes rcsa = new RemoteCacheServerAttributes();
        rcsa.setConfigFileName(propFile);

        Properties prop = RemoteUtils.loadProps(propFile);
        // Properties prop = PropertyLoader.loadProperties( propFile );

        String servicePortStr = prop.getProperty(REMOTE_CACHE_SERVICE_PORT);
        int servicePort = -1;
        try {
            servicePort = Integer.parseInt(servicePortStr);

            rcsa.setServicePort(servicePort);
            log.debug("Remote cache service uses port number " + servicePort + ".");
        } catch (NumberFormatException ignore) {
            log.debug("Remote cache service port property " + REMOTE_CACHE_SERVICE_PORT
                    + " not specified.  An anonymous port will be used.");
        }

        String lccStr = prop.getProperty(REMOTE_LOCAL_CLUSTER_CONSISTENCY);
        if (lccStr == null) {
            lccStr = "true";
        }
        boolean lcc = Boolean.valueOf(lccStr).booleanValue();
        rcsa.setLocalClusterConsistency(lcc);

        String acgStr = prop.getProperty(REMOTE_ALLOW_CLUSTER_GET);
        if (acgStr == null) {
            acgStr = "true";
        }
        boolean acg = Boolean.valueOf(acgStr).booleanValue();
        rcsa.setAllowClusterGet(acg);

        if (log.isInfoEnabled()) {
            log.info("Creating server with these attributes " + rcsa);
        }

        // CREATE SERVER
        remoteCacheServer = new RemoteCacheServer(rcsa);

        if (host == null) {
            host = "";
        }
        // Register the RemoteCacheServer remote object in the registry.
        serviceName = prop.getProperty(REMOTE_CACHE_SERVICE_NAME, REMOTE_CACHE_SERVICE_VAL).trim();

        if (log.isInfoEnabled()) {
            log.info("Binding server to " + host + ":" + port + " with the name " + serviceName);
        }
        try {
            Naming.rebind("//" + host + ":" + port + "/" + serviceName, remoteCacheServer);
        } catch (MalformedURLException ex) {
            // impossible case.
            throw new IllegalArgumentException(ex.getMessage() + "; host=" + host + ", port=" + port);
        }
    }
}

From source file:org.ohie.pocdemo.form.util.ClientRegistryUtil.java

public static Socket connect(final String host, final int port, int nrRetries)
        throws UnknownHostException, IOException {
    final String prop = "100000";
    final int timeout = prop == null ? -1 : Integer.parseInt(prop);

    while (nrRetries-- >= 0) {
        try {/*from   w ww.j  a va2 s .co  m*/
            final Socket rv = new Socket(host, port);
            if (timeout >= 0) {
                rv.setSoTimeout(timeout);
            }

            return rv;
        } catch (final UnknownHostException e) {
            e.fillInStackTrace();
            //Utl.dp("connect failed: unknownHost:", host, port);
            throw e;
        } catch (final IOException e) {
            if (nrRetries < 0) {
                e.fillInStackTrace();
                //Utl.dp("connect failed: connection refused:", host, port);
                throw e;
            }
            // sleep(10);
        }
    }
    throw new HL7IOException("connect nr retries exceeded:" + host + "|" + port + "|" + nrRetries);
}

From source file:org.broad.igv.gitools.Gitools.java

/**
 * Send a command to gitools, and read the response.
 * @param command/*from   www  .  j a  v  a  2s  .  co  m*/
 * @return First line of response only TODO This is stupid but readLine is hanging so hack it for now
 * @throws IOException
 */
private static List<String> sendCommand(String command) throws IOException {
    Socket socket = null;
    try {
        socket = new Socket(host, port);
        socket.setSoTimeout(1000);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.println(command);
        List<String> response = new ArrayList<String>();
        String line;
        while ((line = in.readLine()) != null) {
            response.add(line);
            break;
        }
        return response;

    } catch (IOException e) {
        System.out.println(e);
        throw new IOException("Error communicating with gitools", e);
    } finally {
        if (socket != null)
            socket.close();
    }
}