Example usage for java.net Socket setTcpNoDelay

List of usage examples for java.net Socket setTcpNoDelay

Introduction

In this page you can find the example usage for java.net Socket setTcpNoDelay.

Prototype

public void setTcpNoDelay(boolean on) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#TCP_NODELAY TCP_NODELAY (disable/enable Nagle's algorithm).

Usage

From source file:com.epam.reportportal.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }/*from   w  w  w  .  j a va 2  s.c  o m*/
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.darkphoenixs.pool.socket.SocketConnectionFactory.java

@Override
public Socket createConnection() throws Exception {

    Socket socket = new Socket();

    try {// w  ww .  j  av  a 2 s. co  m
        if (sendBufferSize > 0)
            socket.setSendBufferSize(sendBufferSize);

        if (receiveBufferSize > 0)
            socket.setReceiveBufferSize(receiveBufferSize);

        if (soTimeout > 0)
            socket.setSoTimeout(soTimeout);

        if (linger > 0)
            socket.setSoLinger(true, linger);

        if (keepAlive)
            socket.setKeepAlive(keepAlive);

        if (tcpNoDelay)
            socket.setTcpNoDelay(tcpNoDelay);

        if (performance != null)
            socket.setPerformancePreferences(Integer.parseInt(performance[0]), Integer.parseInt(performance[1]),
                    Integer.parseInt(performance[2]));

        socket.connect(socketAddress, connectionTimeout);

    } catch (Exception se) {
        socket.close();
        throw se;
    }

    return socket;
}

From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }//from  ww  w.j  a va 2s. co  m
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.mycard.net.network.AndroidHttpClientConnection.java

/***
 * Bind socket and set HttpParams to AndroidHttpClientConnection
 * @param socket outgoing socket/*  ww w  . j a  v a  2s  .  com*/
 * @param params HttpParams
 * @throws IOException
  */
public void bind(final Socket socket, final HttpParams params) throws IOException {
    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    assertNotOpen();
    socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

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

    int buffersize = HttpConnectionParams.getSocketBufferSize(params);
    this.inbuffer = new SocketInputBuffer(socket, buffersize, params);
    this.outbuffer = new SocketOutputBuffer(socket, buffersize, params);

    maxHeaderCount = params.getIntParameter(CoreConnectionPNames.MAX_HEADER_COUNT, -1);
    maxLineLength = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);

    this.requestWriter = new HttpRequestWriter(outbuffer, null, params);

    this.metrics = new HttpConnectionMetricsImpl(inbuffer.getMetrics(), outbuffer.getMetrics());

    this.open = true;
}

From source file:org.apache.xmlrpc.WebServer.java

/**
 * Listens for client requests until stopped.  Call {@link
 * #start()} to invoke this method, and {@link #shutdown()} to
 * break out of it./*  w ww .  j av a  2 s .c  o  m*/
 *
 * @throws RuntimeException Generally caused by either an
 * <code>UnknownHostException</code> or <code>BindException</code>
 * with the vanilla web server.
 *
 * @see #start()
 * @see #shutdown()
 */
public void run() {
    try {
        while (listener != null) {
            try {
                Socket socket = serverSocket.accept();
                try {
                    socket.setTcpNoDelay(true);
                } catch (SocketException socketOptEx) {
                    System.err.println(socketOptEx);
                }

                if (allowConnection(socket)) {
                    Runner runner = getRunner();
                    runner.handle(socket);
                } else {
                    socket.close();
                }
            } catch (InterruptedIOException checkState) {
                // Timeout while waiting for a client (from
                // SO_TIMEOUT)...try again if still listening.
            } catch (Exception ex) {
                System.err.println("Exception in XML-RPC listener loop (" + ex + ").");
                if (XmlRpc.debug) {
                    ex.printStackTrace();
                }
            } catch (Error err) {
                System.err.println("Error in XML-RPC listener loop (" + err + ").");
                err.printStackTrace();
            }
        }
    } catch (Exception exception) {
        System.err.println("Error accepting XML-RPC connections (" + exception + ").");
        if (XmlRpc.debug) {
            exception.printStackTrace();
        }
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
                if (XmlRpc.debug) {
                    System.out.print("Closed XML-RPC server socket");
                }
                serverSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Shutdown our Runner-based threads
        if (runners != null) {
            ThreadGroup g = runners;
            runners = null;
            try {
                g.interrupt();
            } catch (Exception e) {
                System.err.println(e);
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    String socksHost = System.getProperty("socksProxyHost");
    Socket s;
    InetSocketAddress addr = new InetSocketAddress(host, port);
    if (socksHost != null) {
        Proxy proxy = new Proxy(Type.SOCKS, new InetSocketAddress(socksHost, 1080));
        s = new Socket(proxy);
        s.connect(addr);/* w  w w .ja v a 2s  . co m*/
    } else {
        log.error(addr);
        SocketChannel sc = SocketChannel.open(addr);
        s = sc.socket();
    }
    s.setTcpNoDelay(true);
    return s;
}

From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java

public void sendCaffeData(double[][] data2, double[][] labels2, double[][] weights, String name,
        boolean ordered, boolean file) {
    double[][] data = new double[data2.length][];
    double[][] labels = new double[data2.length][];
    if (!ordered) {
        for (int i = 0; i < data2.length; i++) {
            data[i] = data2[i].clone();//w ww . ja  va  2 s  . c o m
            labels[i] = labels2[i].clone();
        }
    } else {
        data = data2;
        labels = labels2;
    }
    try {
        String sentence;
        String modifiedSentence;
        Random generator = new Random();
        //set up our socket server

        BufferedReader inFromServer = null;
        DataOutputStream outToServer = null;
        Socket clientSocket = null;

        //add in data in a random order
        if (!file) {
            System.err.println("starting to send on socket");
            clientSocket = new Socket("localhost", 5004);
            clientSocket.setTcpNoDelay(false);
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
            inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(name + "\n");

            outToServer.writeBytes((data.length + " " + data[0].length + " " + labels[0].length) + "\n");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
            }
        } else {
            outToServer = new DataOutputStream((OutputStream) new FileOutputStream(name));
        }
        StringBuffer wholeMessage = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            if (i % 1000 == 0) {
                System.err.println("(constructed) i is " + i);
            }
            String features = "";
            int randomIndex = generator.nextInt(data.length - i);

            if (!ordered) {
                swap(data, i, i + randomIndex);
                swap(labels, i, i + randomIndex);
            }
            for (int a = 0; a < data[i].length; a++) {
                wholeMessage.append(data[i][a] + " ");
            }
            wholeMessage.append("\n");
            String myLabels = "";
            for (int a = 0; a < labels[i].length; a++) {
                wholeMessage.append(labels[i][a] + " ");
            }
            wholeMessage.append("\n");
            wholeMessage.append(weights[i][0] + "");
            wholeMessage.append("\n");
            outToServer.writeBytes(wholeMessage.toString());
            wholeMessage = new StringBuffer();

        }
        System.err.println("total message size is " + wholeMessage.toString().length());

        //outToServer.writeBytes(wholeMessage.toString());
        if (!file) {
            System.err.println("sending done");
            outToServer.writeBytes("done\n");
            System.err.println("waiting for ack...");
            inFromServer.readLine();
            System.err.println("got the ack!");
            clientSocket.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("server wasn't waiting");
    }
    System.err.println("hey i sent somethin!");

}

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 w  w  w  .  ja v  a 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 {/*w  ww . j  a va2  s .  com*/
        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:org.openqa.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/* w  ww  .ja v a 2 s  . c om*/
        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;
    }
}