Search in sources :

Example 86 with Socket

use of java.net.Socket in project XobotOS by xamarin.

the class SocketHandler method initSocket.

// Initialize the socket connection and prepare the output stream
private void initSocket(String host, String port) throws IOException {
    // check the validity of the host name
    if (host == null || host.isEmpty()) {
        throw new IllegalArgumentException("host == null || host.isEmpty()");
    }
    // check the validity of the port number
    int p = 0;
    try {
        p = Integer.parseInt(port);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Illegal port argument");
    }
    if (p <= 0) {
        throw new IllegalArgumentException("Illegal port argument");
    }
    // establish the network connection
    try {
        this.socket = new Socket(host, p);
    } catch (IOException e) {
        getErrorManager().error("Failed to establish the network connection", e, ErrorManager.OPEN_FAILURE);
        throw e;
    }
    super.internalSetOutputStream(new BufferedOutputStream(this.socket.getOutputStream()));
}
Also used : IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream) Socket(java.net.Socket)

Example 87 with Socket

use of java.net.Socket in project XobotOS by xamarin.

the class HttpConnection method isStale.

/**
     * Returns true if the connection is functional. This uses a shameful hack
     * to peek a byte from the socket.
     */
boolean isStale() throws IOException {
    if (!isEligibleForRecycling()) {
        return true;
    }
    InputStream in = getInputStream();
    if (in.available() > 0) {
        return false;
    }
    Socket socket = getSocket();
    int soTimeout = socket.getSoTimeout();
    try {
        socket.setSoTimeout(1);
        in.mark(1);
        int byteRead = in.read();
        if (byteRead != -1) {
            in.reset();
            return false;
        }
        // the socket is reporting all data read; it's stale
        return true;
    } catch (SocketTimeoutException e) {
        // the connection is not stale; hooray
        return false;
    } catch (IOException e) {
        // the connection is stale, the read or soTimeout failed.
        return true;
    } finally {
        socket.setSoTimeout(soTimeout);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 88 with Socket

use of java.net.Socket in project XobotOS by xamarin.

the class HttpConnectionPool method recycle.

public void recycle(HttpConnection connection) {
    final Socket socket = connection.getSocket();
    try {
        SocketTagger.get().untag(socket);
    } catch (SocketException e) {
        // When unable to remove tagging, skip recycling and close
        System.logW("Unable to untagSocket(): " + e);
        connection.closeSocketAndStreams();
        return;
    }
    if (maxConnections > 0 && connection.isEligibleForRecycling()) {
        HttpConnection.Address address = connection.getAddress();
        synchronized (connectionPool) {
            List<HttpConnection> connections = connectionPool.get(address);
            if (connections == null) {
                connections = new ArrayList<HttpConnection>();
                connectionPool.put(address, connections);
            }
            if (connections.size() < maxConnections) {
                connections.add(connection);
                // keep the connection open
                return;
            }
        }
    }
    // don't close streams while holding a lock!
    connection.closeSocketAndStreams();
}
Also used : SocketException(java.net.SocketException) Socket(java.net.Socket)

Example 89 with Socket

use of java.net.Socket in project XobotOS by xamarin.

the class SSLConnectionClosedByUserException method openConnection.

/**
     * Opens the connection to a http server or proxy.
     *
     * @return the opened low level connection
     * @throws IOException if the connection fails for any reason.
     */
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;
    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());
            proxySock.setSoTimeout(60 * 1000);
            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);
            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }
            throw new IOException(errorMessage);
        }
        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());
            // 400 Bad Request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) {
                    proxyReq.addHeader(h);
                }
            }
            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        }
        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();
            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();
            proxyConnection.close();
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
            sslSock.setSoTimeout(SOCKET_TIMEOUT);
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }
            throw new IOException(errorMessage);
        }
    }
    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());
    // Inform the user if there is a problem
    if (error != null) {
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }
    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);
    return conn;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) StatusLine(org.apache.http.StatusLine) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpException(org.apache.http.HttpException) ParseException(org.apache.http.ParseException) BasicHttpParams(org.apache.http.params.BasicHttpParams) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 90 with Socket

use of java.net.Socket in project XobotOS by xamarin.

the class SingleClientConnManager method getConnection.

/**
     * Obtains a connection.
     * This method does not block.
     *
     * @param route     where the connection should point to
     *
     * @return  a connection that can be used to communicate
     *          along the given route
     */
public ManagedClientConnection getConnection(HttpRoute route, Object state) {
    if (route == null) {
        throw new IllegalArgumentException("Route may not be null.");
    }
    assertStillUp();
    if (log.isDebugEnabled()) {
        log.debug("Get connection for route " + route);
    }
    if (managedConn != null)
        revokeConnection();
    // check re-usability of the connection
    boolean recreate = false;
    boolean shutdown = false;
    // Kill the connection if it expired.
    closeExpiredConnections();
    if (uniquePoolEntry.connection.isOpen()) {
        RouteTracker tracker = uniquePoolEntry.tracker;
        shutdown = (// can happen if method is aborted
        tracker == null || !tracker.toRoute().equals(route));
    } else {
        // If the connection is not open, create a new PoolEntry,
        // as the connection may have been marked not reusable,
        // due to aborts -- and the PoolEntry should not be reused
        // either.  There's no harm in recreating an entry if
        // the connection is closed.
        recreate = true;
    }
    if (shutdown) {
        recreate = true;
        try {
            uniquePoolEntry.shutdown();
        } catch (IOException iox) {
            log.debug("Problem shutting down connection.", iox);
        }
    }
    if (recreate)
        uniquePoolEntry = new PoolEntry();
    // updated statistics options.
    try {
        final Socket socket = uniquePoolEntry.connection.getSocket();
        if (socket != null) {
            SocketTagger.get().tag(socket);
        }
    } catch (IOException iox) {
        log.debug("Problem tagging socket.", iox);
    }
    // END android-changed
    managedConn = new ConnAdapter(uniquePoolEntry, route);
    return managedConn;
}
Also used : IOException(java.io.IOException) RouteTracker(org.apache.http.conn.routing.RouteTracker) Socket(java.net.Socket)

Aggregations

Socket (java.net.Socket)1633 IOException (java.io.IOException)705 ServerSocket (java.net.ServerSocket)578 OutputStream (java.io.OutputStream)377 InetSocketAddress (java.net.InetSocketAddress)367 Test (org.junit.Test)362 InputStream (java.io.InputStream)259 InputStreamReader (java.io.InputStreamReader)179 BufferedReader (java.io.BufferedReader)160 SocketException (java.net.SocketException)137 SSLSocket (javax.net.ssl.SSLSocket)111 SocketTimeoutException (java.net.SocketTimeoutException)97 UnknownHostException (java.net.UnknownHostException)86 ConnectException (java.net.ConnectException)84 InetAddress (java.net.InetAddress)78 ByteArrayOutputStream (java.io.ByteArrayOutputStream)76 OutputStreamWriter (java.io.OutputStreamWriter)70 DataOutputStream (java.io.DataOutputStream)68 ServletOutputStream (javax.servlet.ServletOutputStream)68 CountDownLatch (java.util.concurrent.CountDownLatch)65