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:org.parosproxy.paros.core.proxy.WebSocketsConnectionIntegrationTest.java

@Test
public void doAutobahnTest() throws HttpException, SocketException {
    // use HTTP-client with custom connection manager
    // that allows us to expose the SocketChannel
    HttpClient client = new HttpClient(new ZapHttpConnectionManager());
    client.getHostConfiguration().setProxy(PROXY_HOST, PROXY_PORT);

    // create minimal HTTP handshake request
    ZapGetMethod method = new ZapGetMethod("http://localhost:9001/runCase?case=1&agent=Proxy");
    method.addRequestHeader("Connection", "upgrade");
    method.addRequestHeader("Upgrade", "websocket");
    method.addRequestHeader("Sec-WebSocket-Version", "13");
    method.addRequestHeader("Sec-WebSocket-Key", "5d5NazNjJ5hafSgFYJ7SOw==");
    try {/*  w ww .j  a  va 2s. c o m*/
        client.executeMethod(method);
    } catch (IOException e) {
        assertTrue("executing HTTP method failed", false);
    }

    assertEquals("HTTP status code of WebSockets-handshake response should be 101.", 101,
            method.getStatusCode());

    Socket socket = method.getUpgradedConnection();
    socket.setTcpNoDelay(true);
    socket.setSoTimeout(500);

    byte[] dst = new byte[20];
    try {
        socket.getInputStream().read(dst);
    } catch (IOException e) {
        assertTrue("reading websocket frame failed: " + e.getMessage(), false);
    }
}

From source file:com.adaptris.http.HttpListener.java

/** @see Runnable#run() */
public void run() {
    try {/*from w ww .ja  v  a 2  s. c  om*/
        logR.trace("Accepting Connections");
        while (started) {
            try {

                Socket socket = serverSocket.accept();

                // Set the default timeout
                socket.setSoTimeout(socketTimeout);
                dispatcherPool.execute(new RequestDispatcher(socket, requestProcessors, this));
            } catch (Exception e) {
                ;
            }
        }
        try {
            logR.trace("Shutdown requested on the dispatcher pool");
            dispatcherPool.shutdown();
            boolean poolShutdown = dispatcherPool.awaitTermination(SHUTDOWN_WAIT_TIME_MS,
                    TimeUnit.MILLISECONDS);
            if (!poolShutdown) {
                dispatcherPool.shutdownNow();
            }
            logR.trace("Pool is shutdown");
            serverSocket.close();
        } catch (Exception e) {
            ;
        }
    } catch (Exception e) {
        logR.error("Error occured during runtime :- ", e);
    }
    logR.trace("Run-method returns");
}

From source file:UniqueInstance.java

/**
 * Reoit un message d'une socket s'tant connecte au serveur d'coute. Si ce message est le message de l'instance
 * unique, l'application demande le focus.
 *
 * @param socket//from   ww w .jav  a2 s .  com
 * Socket connect au serveur d'coute.
 */
private void receive(Socket socket) {
    Scanner sc = null;

    try {
        /* On n'coute que 5 secondes, si aucun message n'est reu, tant pis... */
        socket.setSoTimeout(5000);

        /* On dfinit un Scanner pour lire sur l'entre de la socket. */
        sc = new Scanner(socket.getInputStream());

        /* On ne lit qu'une ligne. */
        String s = sc.nextLine();

        /* Si cette ligne est le message de l'instance unique... */
        if (message.equals(s)) {
            /* On excute le code demand. */
            runOnReceive.run();
        }
    } catch (IOException e) {
        Logger.getLogger("UniqueInstance").warning("Lecture du flux d'entre de la socket chou.");
    } finally {
        if (sc != null) {
            sc.close();
        }
    }

}

From source file:com.qiniu.android.http.ClientConnectionOperator.java

/**
 * Performs standard initializations on a newly created socket.
 *
 * @param sock    the socket to prepare/*  w  ww .  j av  a 2s  .c o m*/
 * @param context the context for the connection
 * @param params  the parameters from which to prepare the socket
 * @throws IOException in case of an IO problem
 */
protected void prepareSocket(final Socket sock, final HttpContext context, final HttpParams params)
        throws IOException {
    sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

    final int linger = HttpConnectionParams.getLinger(params);
    if (linger >= 0) {
        sock.setSoLinger(linger > 0, linger);
    }
}

From source file:com.dbay.apns4j.impl.ApnsConnectionImpl.java

private Socket createNewSocket() throws IOException, UnknownHostException {
    if (logger.isDebugEnabled()) {
        logger.debug(connName + " create a new socket.");
    }//  www  . j a  va 2 s.c o m
    isFirstWrite = true;
    errorHappendedLastConn = false;
    Socket socket = factory.createSocket(host, port);
    socket.setSoTimeout(readTimeOut);
    // enable tcp_nodelay, any data will be sent immediately.
    socket.setTcpNoDelay(true);

    return socket;
}

From source file:nl.nn.adapterframework.ftp.FTPsClient.java

protected Socket _openDataConnection_(int cmdNr, String param) throws IOException {
    // if explicit FTPS, the socket connection is establisch unsecure
    if (session.getFtpType() == FtpSession.FTPS_EXPLICIT_SSL
            || session.getFtpType() == FtpSession.FTPS_EXPLICIT_TLS) {
        if (session.isProtp()) {
            // With Prot P the result is returned over a different port
            // .. send protp commands  

            sendCommand("PBSZ", "0");
            checkReply("PBSZ 0");
            sendCommand("PROT", "P");
            checkReply("PROT P");
            sendCommand("PASV");
            checkReply("PASV");

            // Parse the host and port name to which the result is send
            String reply = getReplyString();
            String line = reply.substring(reply.indexOf('(') + 1, reply.lastIndexOf(')'));
            String[] hostinfo = line.split(",");
            String host = hostinfo[0] + "." + hostinfo[1] + "." + hostinfo[2] + "." + hostinfo[3];
            int port = (Integer.parseInt(hostinfo[4]) << 8) + Integer.parseInt(hostinfo[5]);
            log.debug("channel from pasv reply=" + host + ":" + port);
            InetSocketAddress address = new InetSocketAddress(host, port);

            // connect to the result address
            Socket socket = new Socket();
            socket.connect(address);/*w w w  .j a va2 s  .co m*/
            socket.setSoTimeout(1000);
            host = socket.getInetAddress().getHostAddress();
            port = socket.getPort();
            log.debug("channel from socket=" + host + ":" + port);
            socket = socketFactory.createSocket(socket, host, port, true);

            String cmdLine = FTPCommand.getCommand(cmdNr);
            if (param != null) {
                cmdLine += ' ' + param;
            }
            // send the requested command (over the original socket)  <-- toch maar niet! GvB
            //            _sendCommand(cmdLine, _socket_.getOutputStream(), null);         
            sendCommand(cmdNr, param);

            // return the new socket for the reply 
            return socket;

        }
    }
    return super._openDataConnection_(cmdNr, param);
}

From source file:org.parosproxy.paros.core.proxy.WebSocketsConnectionIntegrationTest.java

/**
 * Sends a Hello message into the channel and asserts that
 * the same message is returned by the Echo-Server.
 * The outgoing message is masked, while the incoming
 * contains the message in cleartext.//from w  w  w  .ja va 2 s . com
 *
 * @param socket
 * @throws IOException
 */
private void assertWorkingWebSocket(Socket socket) throws IOException {
    assertTrue("Retrieved SocketChannel should not be null.", socket != null);
    socket.setSoTimeout(500);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);

    byte[] maskedHelloMessage = { (byte) 0x81, (byte) 0x85, 0x37, (byte) 0xfa, 0x21, 0x3d, 0x7f, (byte) 0x9f,
            0x4d, 0x51, 0x58 };
    byte[] unmaskedHelloMessage = { (byte) 0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f };

    InputStream inpStream = new BufferedInputStream(socket.getInputStream());

    OutputStream out = socket.getOutputStream();
    out.write(maskedHelloMessage);
    out.flush();

    byte[] dst = new byte[7];
    inpStream.read(dst);

    // use Arrays class to compare two byte arrays
    // returns true if it contains the same elements in same order
    assertTrue("Awaited unmasked hello message from echo server.", Arrays.equals(unmaskedHelloMessage, dst));
}

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

protected void connect(Socket socket) throws IOException {
    InetSocketAddress saddr = getSocketAddress();
    try {/*  w  w  w. ja  v  a  2  s .c  o m*/
        socket.connect(saddr, getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        setMessage("OK");
    } catch (IOException e) {
        setMessage("connect " + saddr, e);
        throw e;
    }
}

From source file:org.archive.wayback.resourcestore.locationdb.FileProxyServlet.java

private DataSource locationToDataSource(String location, long offset) throws IOException {
    DataSource ds = null;/*  w w w  .  j  ava  2s  . c  o m*/
    if (location.startsWith("http://")) {
        URL url = new URL(location);
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = 80;
        }
        byte GET[] = "GET".getBytes();
        byte HTTP11[] = "HTTP/1.1".getBytes();
        InetAddress addr = InetAddress.getByName(hostname);
        HttpRequestMessage requestMessage = new HttpRequestMessage(GET, url.getFile().getBytes(), HTTP11);
        ANVLRecord headers = new ANVLRecord();
        headers.addLabelValue("Host", hostname);

        if (offset != 0) {
            headers.addLabelValue(RANGE_HTTP_HEADER,
                    HEADER_BYTES_PREFIX + String.valueOf(offset) + HEADER_BYTES_SUFFIX);
        }
        InetSocketAddress sockAddr = new InetSocketAddress(addr, port);
        Socket socket = new Socket();
        socket.setSoTimeout(socketTimeoutMs);
        socket.setReceiveBufferSize(BUF_SIZE);

        socket.connect(sockAddr, connectTimeoutMs);
        OutputStream socketOut = socket.getOutputStream();
        InputStream socketIn = socket.getInputStream();
        socketOut.write(requestMessage.getBytes(true));
        socketOut.write(headers.getUTF8Bytes());
        socketOut.flush();
        HttpResponse response = HttpResponse.load(socketIn);
        String contentType = response.getHeaders().asMap().get("Content-Type");
        if (contentType == null) {
            contentType = "application/unknown";
        }
        String xferEncoding = response.getHeaders().asMap().get("Transfer-Encoding");

        if (xferEncoding != null) {
            if (xferEncoding.equals("chunked")) {
                socketIn = new ChunkedInputStream(socketIn);
            }
        }

        ds = new URLDataSource(socketIn, contentType);

    } else {
        // assume a local file path:
        File f = new File(location);
        if (f.isFile() && f.canRead()) {
            long size = f.length();
            if (size < offset) {
                throw new IOException("short file " + location + " cannot" + " seek to offset " + offset);
            }
            RandomAccessFile raf = new RandomAccessFile(f, "r");
            raf.seek(offset);
            // BUGBUG: is it compressed?
            ds = new FileDataSource(raf, DEFAULT_CONTENT_TYPE);

        } else {
            throw new IOException("No readable file at " + location);
        }

    }

    return ds;
}

From source file:com.owncloud.android.authenticator.EasySSLSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//w ww. j  a v a  2  s . c om
 * <p>
 * To circumvent the limitations of older JREs that do not support connect
 * timeout a controller thread is executed. The controller thread attempts
 * to create a new socket within the given limit of time. If socket
 * constructor does not return until the timeout expires, the controller
 * terminates and throws an {@link ConnectTimeoutException}
 * </p>
 * 
 * @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
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Log.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();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    /*if (timeout == 0) {
    Log.d(TAG, " ... with connection timeout 0 and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket(host, port, localAddress,
            localPort);
    socket.setSoTimeout(params.getSoTimeout());
    return socket;
    } else {*/
    Log.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    socket.connect(remoteaddr, timeout);
    return socket;
    //}
}