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:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit./*w w w .  j a v  a  2s. c o  m*/
  * 
  * @param host the host name/IP
  * @param port the port on the host
  * @param clientHost the local host name/IP to bind the socket to
  * @param clientPort the port on the local machine
  * @param params {@link HttpConnectionParams Http connection parameters}
  * 
  * @return Socket a new socket
  * 
  * @throws IOException if an I/O error occurs while creating the socket
  * @throws UnknownHostException if the IP address of the host cannot be
  *             determined
  */
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    //logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    enableSecureProtocols(socket);
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeVolumeFailure.java

/**
 * try to access a block on a data node. If fails - throws exception
 * @param datanode/*  ww w.  j  a v  a  2  s .c om*/
 * @param lblock
 * @throws IOException
 */
private void accessBlock(DatanodeInfo datanode, LocatedBlock lblock) throws IOException {
    InetSocketAddress targetAddr = null;
    Socket s = null;
    ExtendedBlock block = lblock.getBlock();

    targetAddr = NetUtils.createSocketAddr(datanode.getName());

    s = new Socket();
    s.connect(targetAddr, HdfsServerConstants.READ_TIMEOUT);
    s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);

    String file = BlockReaderFactory.getFileName(targetAddr, "test-blockpoolid", block.getBlockId());
    BlockReader blockReader = BlockReaderFactory.newBlockReader(s, file, block, lblock.getBlockToken(), 0, -1,
            4096);

    // nothing - if it fails - it will throw and exception
}

From source file:org.apache.hadoop.dfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf./*from  w  ww  .  j  av a  2 s.  c o  m*/
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, FSConstants.READ_TIMEOUT);
        sock.setSoTimeout(FSConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

From source file:org.opennms.netmgt.provision.detector.msexchange.client.MSExchangeDetectorClient.java

private String connectAndGetResponse(final InetAddress address, final Integer port, final int timeout) {
    Socket socket = null;
    InputStreamReader isr = null;
    BufferedReader lineRdr = null;

    if (port != null) {
        try {/*from   w  w  w  .  j  av a 2  s .com*/
            socket = new Socket();
            final InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port.intValue());
            socket.connect(inetSocketAddress, timeout);
            socket.setSoTimeout(timeout);

            // Allocate a line reader
            isr = new InputStreamReader(socket.getInputStream());
            lineRdr = new BufferedReader(isr);

            // Read the banner line and see if it contains the
            // substring "Microsoft Exchange"
            //
            final String banner = lineRdr.readLine();

            socket.close();
            return banner;

        } catch (final Exception e) {
            LOG.debug("An error occurred while connecting to {}:{}", InetAddressUtils.str(address), port, e);
            IOUtils.closeQuietly(lineRdr);
            IOUtils.closeQuietly(isr);
            if (socket != null) {
                try {
                    socket.close();
                } catch (final IOException e1) {
                    LOG.debug("Additionally, an exception occurred while trying to close the socket.", e);
                }
            }
        }
    }
    return null;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*from   w w  w  .j a va  2  s.  com*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWSecureSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int,org.apache.commons.httpclient.params.HttpConnectionParams)
 */// w  w w.  j  av a2 s  .co m
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort,
        HttpConnectionParams params)
        throws IOException, UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException {

    Socket socket = createSocket(host, port, clientHost, clientPort);
    if (socket != null) {
        // socket.setKeepAlive(false);
        if (params.getReceiveBufferSize() >= 0)
            socket.setReceiveBufferSize(params.getReceiveBufferSize());
        if (params.getSendBufferSize() >= 0)
            socket.setSendBufferSize(params.getSendBufferSize());
        socket.setReuseAddress(true);
        if (params.getSoTimeout() >= 0)
            socket.setSoTimeout(params.getSoTimeout());
    }
    return socket;

}

From source file:org.apache.hadoop.hdfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf./*from  w  w  w  .  ja  v a 2s  . c o  m*/
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, HdfsConstants.READ_TIMEOUT);
        sock.setSoTimeout(HdfsConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

From source file:cloud.elasticity.elastman.Sensor.java

public synchronized void addClient(Socket cs) {
    try {/* ww w  .  ja va 2 s .  co m*/
        cs.setSoTimeout(40000); // wait max 40 seconds;
    } catch (SocketException e) {
        log.error("Error: Can't set socket time out!");
        log.error(e.getMessage());
    }
    clientSockets.add(new MyIO(cs));
    log.info("Client added: {}", cs.getInetAddress());
}

From source file:org.pluroid.pluroium.HttpClientFactory.java

public Socket connectSocket(Socket socket, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (socket == null) {
        socket = createSocket();/*w w w .  j  a  v  a2 s  .c  o  m*/
    }
    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0) {
            localPort = 0; // indicates "any"
        }
        socket.bind(new InetSocketAddress(localAddress, localPort));
    }
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.connect(new InetSocketAddress(host, port), HttpConnectionParams.getConnectionTimeout(params));
    return socket;
}

From source file:com.smartmarmot.orabbix.Sender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    //message.append(Base64.encode(key));
    message.append(base64Encode(key));/*  ww  w . j  av a 2  s . co m*/
    message.append(middle);
    //message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    if (log.isDebugEnabled()) {
        SmartLogger.logThis(Level.DEBUG, "sending " + message);
    }

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    Enumeration<String> serverlist = zabbixServers.keys();

    while (serverlist.hasMoreElements()) {
        String zabbixServer = serverlist.nextElement();
        try {
            zabbix = new Socket(zabbixServer, zabbixServers.get(zabbixServer).intValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            if (log.isDebugEnabled()) {
                SmartLogger.logThis(Level.DEBUG, "received " + new String(response));
            }
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                SmartLogger.logThis(Level.WARN,
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            SmartLogger.logThis(Level.ERROR, "Error contacting Zabbix server " + zabbixServer + "  on port "
                    + zabbixServers.get(zabbixServer));
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}