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.apache.axis.transport.http.HTTPSender.java

/**
 * Creates a socket connection to the SOAP server
 *
 * @param protocol "http" for standard, "https" for ssl.
 * @param host host name//from www .j a v a  2 s.co m
 * @param port port to connect to
 * @param otherHeaders buffer for storing additional headers that need to be sent
 * @param useFullURL flag to indicate if the complete URL has to be sent
 *
 * @throws IOException
 */
protected void getSocket(SocketHolder sockHolder, MessageContext msgContext, String protocol, String host,
        int port, int timeout, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception {
    Hashtable options = getOptions();
    if (timeout > 0) {
        if (options == null) {
            options = new Hashtable();
        }
        options.put(DefaultSocketFactory.CONNECT_TIMEOUT, Integer.toString(timeout));
    }
    SocketFactory factory = SocketFactoryFactory.getFactory(protocol, options);
    if (factory == null) {
        throw new IOException(Messages.getMessage("noSocketFactory", protocol));
    }
    Socket sock = factory.create(host, port, otherHeaders, useFullURL);
    if (timeout > 0) {
        sock.setSoTimeout(timeout);
    }
    sockHolder.setSocket(sock);
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/*from  www  .  j a va 2  s  .co m*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(net.lightbody.bmp.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:org.browsermob.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/*from   w  w w  . j a va  2 s .  c  o  m*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(org.browsermob.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Opens a client socket to the specified port. If this is successful
 * then the port is returned, otherwise it is closed and null is
 * returned./*from  ww  w.  j  a  v  a 2  s.co m*/
 * 
 * @param appId
 *            The application ID.
 * @param port
 *            The port number to connect to.
 * @return The client socket or null if no connection to
 *         the server was possible or the server is not the same
 *         application.
 */
private Socket openClientSocket(String appId, int port) {
    try {
        Socket socket = new Socket(InetAddress.getByName(null), port);
        try {
            // Open communication channels
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));

            // Read the appId from the server. Use a one second timeout for
            // this just in case some unresponsive application listens on
            // this port.
            socket.setSoTimeout(1000);
            String serverAppId = in.readLine();
            socket.setSoTimeout(0);

            // Abort if server app ID doesn't match (Or there was none at
            // all)
            if (serverAppId == null || !serverAppId.equals(appId)) {
                socket.close();
                socket = null;
            }

            return socket;
        } catch (IOException e) {
            socket.close();
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:org.openqa.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {//from   w w  w  .j a v a2  s.co m
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString().getBytes(org.openqa.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

public HttpResponse(HttpBase http, URL url, WebPage page) throws ProtocolException, IOException {
    conf = http.getConf();/*from ww w.java  2  s  . c  om*/
    this.http = http;
    this.url = url;
    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new HttpException("Unknown scheme (not http/https) for url:" + url);
    }

    if (Http.LOG.isTraceEnabled()) {
        Http.LOG.trace("fetching " + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) {
            String ipString = sockAddr.getAddress().getHostAddress(); // get the ip
                                                                      // address
            page.getMetadata().put(new Utf8("_ip_"), ByteBuffer.wrap(ipString.getBytes()));
        }

        Http.LOG.debug("HTTP fetching: " + url);
        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (Http.LOG.isErrorEnabled()) {
                Http.LOG.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        // if (page.isReadable(WebPage.Field.MODIFIED_TIME.getIndex())) {
        reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(page.getModifiedTime()));
        reqStr.append("\r\n");
        // }
        reqStr.append("\r\n");

        byte[] reqBytes = reqStr.toString().getBytes();

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE),
                        Http.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is "Continue"
        }

        if (!url.toString().endsWith("robots.txt")) {
            if (readPlainContent(url.toString(), in)) {
            } else if (readPlainContentByHtmlunit(url)) {
            } else {
                readPlainContentByWebDriver(url);
            }
        }

        if (content != null && content.length > 0) {
            String html = charset == null ? new String(content) : new String(content, charset);
            //System.out.println("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
            Http.LOG_HTML.trace("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
        }

        // add headers in metadata to row
        if (page.getHeaders() != null) {
            page.getHeaders().clear();
        }
        for (String key : headers.names()) {
            page.getHeaders().put(new Utf8(key), new Utf8(headers.get(key)));
        }

    } catch (Exception e) {
        Http.LOG.error(e.getMessage(), e);
    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:hudson.remoting.Engine.java

/**
 * Connects to TCP slave port, with a few retries.
 *//*from   www.j a  v  a  2 s  .  c  om*/
private Socket connect(String port) throws IOException, InterruptedException {
    String host = this.hudsonUrl.getHost();

    if (tunnel != null) {
        String[] tokens = tunnel.split(":", 3);
        if (tokens.length != 2)
            throw new IOException("Illegal tunneling parameter: " + tunnel);
        if (tokens[0].length() > 0)
            host = tokens[0];
        if (tokens[1].length() > 0)
            port = tokens[1];
    }

    String msg = "Connecting to " + host + ':' + port;
    listener.status(msg);
    int retry = 1;
    while (true) {
        try {
            Socket s = new Socket(host, Integer.parseInt(port));
            s.setTcpNoDelay(true); // we'll do buffering by ourselves

            // set read time out to avoid infinite hang. the time out should be long enough so as not
            // to interfere with normal operation. the main purpose of this is that when the other peer dies
            // abruptly, we shouldn't hang forever, and at some point we should notice that the connection
            // is gone.
            s.setSoTimeout(30 * 60 * 1000); // 30 mins. See PingThread for the ping interval
            return s;
        } catch (IOException e) {
            if (retry++ > 10)
                throw (IOException) new IOException("Failed to connect to " + host + ':' + port).initCause(e);
            Thread.sleep(1000 * 10);
            listener.status(msg + " (retrying:" + retry + ")", e);
        }
    }
}

From source file:org.apache98.hadoop.hbase.ipc.RpcClient.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "IS2_INCONSISTENT_SYNC", justification = "Presume sync not needed setting socket timeout")
private static void setSocketTimeout(final Socket socket, final int rpcTimeout)
        throws java.net.SocketException {
    if (socket == null) {
        return;//from  w  w w  .j  a  v a 2 s.  c o  m
    }
    socket.setSoTimeout(rpcTimeout);
}

From source file:org.sandrob.android.net.http.HttpsConnection.java

/**
 * Opens the connection to a http server or proxy.
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *//* w ww  . java  2s  .  c  o  m*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;

    synchronized (HttpsConnection.class) {
        initializeEngine(null, req);
    }
    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());

            // add all 'proxy' headers from the original request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) {
                    proxyReq.addHeader(h);
                }
            }

            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();

            // it is possible to receive informational status
            // codes prior to receiving actual headers;
            // all those status codes are smaller than OK 200
            // 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();

            // here, we return null to indicate that the original
            // 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();

            sslSock.setSoTimeout(SOCKET_TIMEOUT);
            sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()));
        } 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) {
        // handleSslErrorRequest may immediately unsuspend if it wants to
        // allow the certificate anyway.
        // So we mark the connection as suspended, call handleSslErrorRequest
        // then check if we're still suspended and only wait if we actually
        // 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;
}

From source file:org.apache.hadoop.raid.BlockFixer.java

/**
 * Send a generated block to a datanode.
 * @param datanode Chosen datanode name in host:port form.
 * @param blockContents Stream with the block contents.
 * @param corruptBlock Block identifying the block to be sent.
 * @param blockSize size of the block./*from   ww w .  j a v a  2  s . co  m*/
 * @throws IOException
 */
private void sendFixedBlock(DatanodeInfo datanode, final InputStream blockContents, DataInputStream metadataIn,
        LocatedBlock block, long blockSize) throws IOException {
    InetSocketAddress target = NetUtils.createSocketAddr(datanode.name);
    Socket sock = SocketChannel.open().socket();

    int readTimeout = getConf().getInt(BLOCKFIX_READ_TIMEOUT, HdfsConstants.READ_TIMEOUT);
    NetUtils.connect(sock, target, readTimeout);
    sock.setSoTimeout(readTimeout);

    int writeTimeout = getConf().getInt(BLOCKFIX_WRITE_TIMEOUT, HdfsConstants.WRITE_TIMEOUT);

    OutputStream baseStream = NetUtils.getOutputStream(sock, writeTimeout);
    DataOutputStream out = new DataOutputStream(
            new BufferedOutputStream(baseStream, FSConstants.SMALL_BUFFER_SIZE));

    boolean corruptChecksumOk = false;
    boolean chunkOffsetOK = false;
    boolean verifyChecksum = true;
    boolean transferToAllowed = false;

    try {
        LOG.info("Sending block " + block.getBlock() + " from " + sock.getLocalSocketAddress().toString()
                + " to " + sock.getRemoteSocketAddress().toString() + " " + blockSize + " bytes");
        RaidBlockSender blockSender = new RaidBlockSender(block.getBlock(), blockSize, 0, blockSize,
                corruptChecksumOk, chunkOffsetOK, verifyChecksum, transferToAllowed, metadataIn,
                new RaidBlockSender.InputStreamFactory() {
                    @Override
                    public InputStream createStream(long offset) throws IOException {
                        // we are passing 0 as the offset above, so we can safely ignore
                        // the offset passed
                        return blockContents;
                    }
                });

        DatanodeInfo[] nodes = new DatanodeInfo[] { datanode };
        DataTransferProtocol.Sender.opWriteBlock(out, block.getBlock(), 1,
                DataTransferProtocol.BlockConstructionStage.PIPELINE_SETUP_CREATE, 0, blockSize, 0, "", null,
                nodes, block.getBlockToken());
        blockSender.sendBlock(out, baseStream);

        LOG.info("Sent block " + block.getBlock() + " to " + datanode.name);
    } finally {
        out.close();
    }
}