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:net.sbbi.upnp.jmx.UPNPMBeanDevicesRequestsHandler.java

public void run() {
    try {//from  ww  w .ja  va 2  s .co m
        srv = new ServerSocket(bindAddress.getPort(), 200, bindAddress.getAddress());
    } catch (IOException ex) {
        log.error("Error during server socket creation, thread cannot start", ex);
        return;
    }
    isRunning = true;
    while (isRunning) {
        try {
            Socket skt = srv.accept();
            skt.setSoTimeout(30000);
            HttpWorker worker = new HttpWorker(skt, log, handledDevices, this);
            while (httpWorkers.size() >= MAX_HTTP_WORKERS) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    // ignore
                }
            }
            Thread workerThread = new Thread(worker,
                    "UPNPMBeanDevicesRequestsHandler Http Worker " + httpWorkers.size());
            workerThread.start();
            synchronized (httpWorkers) {
                httpWorkers.add(worker);
            }
        } catch (IOException ex) {
            if (isRunning) {
                log.error("Error during client socket creation", ex);
            }
        }
    }
}

From source file:org.apache.isis.objectstore.nosql.db.file.FileServerDb.java

private ClientConnection getConnection() {
    try {/* w  ww  .j a v  a2  s  .  c  o m*/
        final Socket socket;
        socket = new Socket(host, port);
        socket.setSoTimeout(timeout);
        return new ClientConnection(socket.getInputStream(), socket.getOutputStream());
    } catch (final UnknownHostException e) {
        throw new NoSqlStoreException("Unknow host " + host, e);
    } catch (final IOException e) {
        throw new NoSqlStoreException("Failed to connect to " + host + ":" + port, e);
    }

}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

/**
 * Configures socket with any options needed.
 * <p>/*from  w w  w.  j  ava  2 s  . c  o m*/
 * Normally, the client using this factory would call {@link #createSocket(HttpContext)} and then configure the
 * socket. And indeed, it ({@link org.apache.http.impl.conn.DefaultHttpClientConnectionOperator}) does.
 * However, that socket is thrown away in {@link #connectSocket(int, Socket, HttpHost, InetSocketAddress,
 * InetSocketAddress, HttpContext)})
 * So apply here any configurations you actually want enabled.
 *
 * @param socket The socket to be configured
 * @throws SocketException
 */
private void configureSocket(Socket socket) throws SocketException {
    socket.setSoTimeout(SystemProperties.getClientProxyHttpClientTimeout());

    int linger = SystemProperties.getClientProxyHttpClientSoLinger();
    socket.setSoLinger(linger >= 0, linger);
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void afterReadyInterestIsCleared() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);//  w  w  w .j  ava  2s  .c om
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void noReadyCallbackIfInterestRemoved() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/* w  w w .j  ava  2 s . c om*/
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });

    // Wait for registration, in other case we get unpredictable timing related results due to late registration
    while (key.get() == null) {
        Thread.sleep(10);
    }

    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    hub.hub().removeInterestAccept(key.get());
    // wait for the interest accept to be removed
    while ((key.get().interestOps() & SelectionKey.OP_ACCEPT) != 0) {
        Thread.sleep(10);
    }
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.springframework.boot.devtools.livereload.LiveReloadServer.java

private void acceptConnections() {
    do {//from   w  ww  . ja v a2  s . c o m
        try {
            Socket socket = this.serverSocket.accept();
            socket.setSoTimeout(READ_TIMEOUT);
            this.executor.execute(new ConnectionHandler(socket));
        } catch (SocketTimeoutException ex) {
            // Ignore
        } catch (Exception ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("LiveReload server error", ex);
            }
        }
    } while (!this.serverSocket.isClosed());
}

From source file:com.alibaba.wasp.zookeeper.ZKUtil.java

/**
 * Gets the statistics from the given server.
 *
 * @param server//  w ww  . j  a va  2  s  .  c  o m
 *          The server to get the statistics from.
 * @param timeout
 *          The socket timeout to use.
 * @return The array of response strings.
 * @throws java.io.IOException
 *           When the socket communication fails.
 */
public static String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    if (sp == null || sp.length == 0) {
        return null;
    }

    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);

    socket.setSoTimeout(timeout);
    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();
    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null) {
            res.add(line);
        } else {
            break;
        }
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

From source file:org.hyperic.hq.plugin.netservices.NetServicesCollector.java

public SocketWrapper getSocketWrapper(boolean acceptUnverifiedCertificatesOverride) throws IOException {
    if (isSSL()) {
        // Sometimes we may want to override what's set in the keystore config...mostly for init purposes...
        boolean accept = acceptUnverifiedCertificatesOverride ? true : keystoreConfig.isAcceptUnverifiedCert();
        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, accept);
        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();
        Socket socket = factory.createSocket();

        socket.connect(getSocketAddress(), getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        ((SSLSocket) socket).startHandshake();

        return new SocketWrapper(socket);
    } else {/*from   ww  w . j av a 2s.  co m*/
        Socket socket = new Socket();
        connect(socket);
        return new SocketWrapper(socket);
    }
}

From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java

@Override
public void run() {
    try {// w  w  w  .ja va 2  s  . co  m

        LOG.debug("Beginning certificate validation - will connect directly to {} port {}", host,
                String.valueOf(port));

        try {
            LOG.debug("Trying handshake first in case the socket is SSL/TLS only");
            connectToSSLSocket(null);
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, true);
                }
            });
        } catch (final Exception e) {

            if (Networks.extractCertificateValidationException(e) != null) {
                throw e;
            }

            LOG.debug("Direct connection failed or no certificate was presented", e);

            if (serverType == ServerType.HTTPS) {
                postValidationHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onWorkflowFinished(context, e, false);
                    }
                });
                return;
            }

            LOG.debug("Now attempting to connect over plain socket");
            Socket plainSocket = new Socket(host, port);
            plainSocket.setSoTimeout(30000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(plainSocket.getOutputStream()));
            String line;

            if (serverType == ServerType.SMTP) {
                LOG.debug("CLIENT: EHLO localhost");
                writer.write("EHLO localhost\r\n");
                writer.flush();
                line = reader.readLine();
                LOG.debug("SERVER: " + line);
            }

            String command = "", regexToMatch = "";
            if (serverType == ServerType.FTP) {

                LOG.debug("FTP type server");
                command = "AUTH SSL\r\n";
                regexToMatch = "(?:234.*)";

            } else if (serverType == ServerType.SMTP) {

                LOG.debug("SMTP type server");
                command = "STARTTLS\r\n";
                regexToMatch = "(?i:220 .* Ready.*)";

            }

            LOG.debug("CLIENT: " + command);
            LOG.debug("(Expecting regex {} in response)", regexToMatch);
            writer.write(command);
            writer.flush();
            while ((line = reader.readLine()) != null) {
                LOG.debug("SERVER: " + line);
                if (line.matches(regexToMatch)) {
                    LOG.debug("Elevating socket and attempting handshake");
                    connectToSSLSocket(plainSocket);
                    postValidationHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onWorkflowFinished(context, null, true);
                        }
                    });
                    return;
                }
            }

            LOG.debug("No certificates found.  Giving up.");
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, false);
                }
            });
        }

    } catch (final Exception e) {

        LOG.debug("", e);
        postValidationHandler.post(new Runnable() {
            @Override
            public void run() {
                onWorkflowFinished(context, e, false);
            }
        });
    }

}

From source file:demo.socket.pool.SocketsPool.java

private PooledSocketConn createConn(boolean printLog) throws IOException {

    Socket s = new Socket(host, port);
    if (socketSoTimeout != null)
        s.setSoTimeout(socketSoTimeout);

    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    if (printLog)
        log.info("Connected to " + host + ":" + port + "." + " Pool props [" + "maxActiveConnections="
                + poolMaximumActiveConnections + ", maxIdleConnections=" + poolMaximumIdleConnections
                + ", maxCheckoutTime=" + poolMaximumCheckoutTime + ", timeToWait=" + poolTimeToWait + "]");
    return new PooledSocketConn(s, is, os, this);
}