Java Code Examples for java.net.Socket.setTcpNoDelay()

The following are Jave code examples for showing how to use setTcpNoDelay() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: APacheSynapseSimplePOC   File: JenkinsCLI.java   View Source Code Vote up 10 votes
public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
    System.err.println("* Opening socket " + isa);
    Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
    s.setKeepAlive(true);
    s.setTcpNoDelay(true);

    System.err.println("* Opening channel");
    OutputStream outputStream = s.getOutputStream();
    DataOutputStream dos = new DataOutputStream(outputStream);
    dos.writeUTF("Protocol:CLI-connect");
    ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread ( Runnable r ) {
            Thread t = new Thread(r, "Channel");
            t.setDaemon(true);
            return t;
        }
    });
    Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
    System.err.println("* Channel open");
    return c;
}
 
Example 2
Project: feeyo-redisproxy   File: JedisConnection.java   View Source Code Vote up 6 votes
public void connect() {

		if (!isConnected()) {

			try {
				socket = new Socket();
				socket.setReuseAddress(true);
				socket.setKeepAlive(true);
				socket.setTcpNoDelay(true);
				socket.setSoLinger(true, 0);
				
				socket.connect(new InetSocketAddress(host, port), connectionTimeout);
				if ( soTimeout > 0)
		          socket.setSoTimeout(soTimeout);
		        
		        outputStream = new RedisOutputStream(socket.getOutputStream());
		        inputStream = new RedisInputStream(socket.getInputStream());
		        
			} catch (IOException ex) {
				broken = true;
				throw new JedisConnectionException("Failed connecting to host " + host + ":" + port, ex);
			}
		}
	}
 
Example 3
Project: boohee_v5.6   File: u.java   View Source Code Vote up 6 votes
private static boolean b(String str) {
    long currentTimeMillis = System.currentTimeMillis();
    try {
        b.a("ConnectivityTest: begin to connect to " + str);
        Socket socket = new Socket();
        socket.connect(Host.b(str, 5222), BaseImageDownloader.DEFAULT_HTTP_CONNECT_TIMEOUT);
        socket.setTcpNoDelay(true);
        b.a("ConnectivityTest: connect to " + str + " in " + (System.currentTimeMillis() -
                currentTimeMillis));
        socket.close();
        return true;
    } catch (Throwable th) {
        b.d("ConnectivityTest: could not connect to:" + str + " exception: " + th.getClass()
                .getSimpleName() + " description: " + th.getMessage());
        return false;
    }
}
 
Example 4
Project: crush   File: DRPMessenger.java   View Source Code Vote up 6 votes
private synchronized void send(Message message) throws IOException {
	if(message == null) return;
			
	Socket socket = new Socket();
	socket.setReuseAddress(true);
	socket.setPerformancePreferences(2, 1, 0); // connection, latency, bandwidth
	socket.setTcpNoDelay(true);
	socket.setTrafficClass(0x10);	// low delay
	socket.setSoTimeout(timeoutMillis);
	socket.connect(address);
		
	@SuppressWarnings("resource")
       OutputStream out = socket.getOutputStream();
	
	// TODO additional check. Is it needed?
	if(out == null) throw new IOException("Socket has no output stream.");
	
	String text = message.toString();
	out.write(text.getBytes());
	
	if(CRUSH.debug) CRUSH.debug(this, "DRP> " + text);
	
	out.flush();
	socket.close();
}
 
Example 5
Project: FirefoxData-android   File: DefaultHttpClientConnection.java   View Source Code Vote up 6 votes
@Override
public void bind(
        final Socket socket,
        final HttpParams params) throws IOException {
    Args.notNull(socket, "Socket");
    Args.notNull(params, "HTTP parameters");
    assertNotOpen();
    socket.setTcpNoDelay(params.getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true));
    socket.setSoTimeout(params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0));
    socket.setKeepAlive(params.getBooleanParameter(CoreConnectionPNames.SO_KEEPALIVE, false));
    final int linger = params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
    if (linger >= 0) {
        socket.setSoLinger(linger > 0, linger);
    }
    super.bind(socket, params);
}
 
Example 6
Project: incubator-netbeans   File: CommonWireIOTestCase.java   View Source Code Vote up 5 votes
public WireIO createWireIO(Socket clientSocket) {
    try {
        clientSocket.setTcpNoDelay(true); // Necessary at least on Solaris to avoid delays in e.g. readInt() etc.

        ObjectInputStream socketIn = new ObjectInputStream(clientSocket.getInputStream());
        ObjectOutputStream socketOut = new ObjectOutputStream(clientSocket.getOutputStream());
        WireIO wireIO = new WireIO(socketOut, socketIn);

        return wireIO;
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example 7
Project: hadoop   File: TcpPeerServer.java   View Source Code Vote up 5 votes
public static Peer peerFromSocket(Socket socket)
    throws IOException {
  Peer peer = null;
  boolean success = false;
  try {
    // TCP_NODELAY is crucial here because of bad interactions between
    // Nagle's Algorithm and Delayed ACKs. With connection keepalive
    // between the client and DN, the conversation looks like:
    //   1. Client -> DN: Read block X
    //   2. DN -> Client: data for block X
    //   3. Client -> DN: Status OK (successful read)
    //   4. Client -> DN: Read block Y
    // The fact that step #3 and #4 are both in the client->DN direction
    // triggers Nagling. If the DN is using delayed ACKs, this results
    // in a delay of 40ms or more.
    //
    // TCP_NODELAY disables nagling and thus avoids this performance
    // disaster.
    socket.setTcpNoDelay(true);
    SocketChannel channel = socket.getChannel();
    if (channel == null) {
      peer = new BasicInetPeer(socket);
    } else {
      peer = new NioInetPeer(socket);
    }
    success = true;
    return peer;
  } finally {
    if (!success) {
      if (peer != null) peer.close();
      socket.close();
    }
  }
}
 
Example 8
Project: urdriver   File: URClient.java   View Source Code Vote up 5 votes
public void connect() throws UnknownHostException, IOException {
	LOG.log(Level.INFO, "connecting to " + host + ":" +  port);
	socket = new Socket(host, port);
	socket.setTcpNoDelay(true);
	socket.setSoTimeout(DEFAULT_TIMEOUT);
	in = socket.getInputStream();
	writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
	thread = new URClientThread(name);
	thread.start();
	connected = true;
}
 
Example 9
Project: fdt   File: GUIControlChannel.java   View Source Code Vote up 5 votes
/**
 * Try to connect to a remote FDT instance
 *
 * @param inetAddress
 * @param port
 * @param notifier
 * @throws Exception
 */
public GUIControlChannel(InetAddress inetAddress, int port, GUIControlChannelNotifier notifier) throws Exception {
    try {
        this.notifier = notifier;

        controlSocket = new Socket();
        controlSocket.connect(new InetSocketAddress(inetAddress, port), CONNECT_TIMEOUT);

        this.remoteAddress = inetAddress;
        this.remotePort = port;
        this.localPort = controlSocket.getLocalPort();

        controlSocket.setTcpNoDelay(true);

        //only the first octet will be interpreted by the AcceptTask at the other end
        controlSocket.getOutputStream().write(new byte[]{3});

        //from now on only CtrlMsg will be sent
        initStreams();
        controlSocket.setSoTimeout(1000);

        //
    } catch (Throwable t) {
        close("Cannot instantiate ControlChannel", t);
        throw new Exception(t);
    }
}
 
Example 10
Project: openjdk-jdk10   File: DefaultSocketFactoryImpl.java   View Source Code Vote up 5 votes
public void setAcceptedSocketOptions(Acceptor acceptor,
                                     ServerSocket serverSocket,
                                     Socket socket)
    throws SocketException
{
    // Disable Nagle's algorithm (i.e., always send immediately).
    socket.setTcpNoDelay(true);
    if (keepAlive)
        socket.setKeepAlive(true);
}
 
Example 11
Project: lams   File: JIoEndpoint.java   View Source Code Vote up 5 votes
/**
 * Set the options for the current socket.
 */
protected boolean setSocketOptions(Socket socket) {
    // Process the connection
    int step = 1;
    try {

        // 1: Set socket options: timeout, linger, etc
        if (soLinger >= 0) { 
            socket.setSoLinger(true, soLinger);
        }
        if (tcpNoDelay) {
            socket.setTcpNoDelay(tcpNoDelay);
        }
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }

        // 2: SSL handshake
        step = 2;
        serverSocketFactory.handshake(socket);

    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            if (step == 2) {
                log.debug(sm.getString("endpoint.err.handshake"), t);
            } else {
                log.debug(sm.getString("endpoint.err.unexpected"), t);
            }
        }
        // Tell to close the socket
        return false;
    }
    return true;
}
 
Example 12
Project: apache-tomcat-7.0.73-with-comment   File: BioSender.java   View Source Code Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled
 * is socket open return directly
 */
protected void openSocket() throws IOException {
   if(isConnected()) return ;
   try {
       socket = new Socket();
       InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
       socket.connect(sockaddr,(int)getTimeout());
       socket.setSendBufferSize(getTxBufSize());
       socket.setReceiveBufferSize(getRxBufSize());
       socket.setSoTimeout( (int) getTimeout());
       socket.setTcpNoDelay(getTcpNoDelay());
       socket.setKeepAlive(getSoKeepAlive());
       socket.setReuseAddress(getSoReuseAddress());
       socket.setOOBInline(getOoBInline());
       socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
       socket.setTrafficClass(getSoTrafficClass());
       setConnected(true);
       soOut = socket.getOutputStream();
       soIn  = socket.getInputStream();
       setRequestCount(0);
       setConnectTime(System.currentTimeMillis());
       if (log.isDebugEnabled())
           log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)));
  } catch (IOException ex1) {
      SenderState.getSenderState(getDestination()).setSuspect();
      if (log.isDebugEnabled())
          log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
      throw (ex1);
    }
    
 }
 
Example 13
Project: FirefoxData-android   File: DefaultClientConnectionOperator.java   View Source Code Vote up 5 votes
/**
 * Performs standard initializations on a newly created socket.
 *
 * @param sock      the socket to prepare
 * @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);
    }
}
 
Example 14
Project: java-android-websocket-client   File: BasicConnFactory.java   View Source Code Vote up 5 votes
@Override
public HttpClientConnection create(final HttpHost host) throws IOException {
    final String scheme = host.getSchemeName();
    Socket socket = null;
    if ("http".equalsIgnoreCase(scheme)) {
        socket = this.plainfactory != null ? this.plainfactory.createSocket() :
                new Socket();
    } if ("https".equalsIgnoreCase(scheme)) {
        socket = (this.sslfactory != null ? this.sslfactory :
                SSLSocketFactory.getDefault()).createSocket();
    }
    if (socket == null) {
        throw new IOException(scheme + " scheme is not supported");
    }
    final String hostname = host.getHostName();
    int port = host.getPort();
    if (port == -1) {
        if (host.getSchemeName().equalsIgnoreCase("http")) {
            port = 80;
        } else if (host.getSchemeName().equalsIgnoreCase("https")) {
            port = 443;
        }
    }
    socket.setSoTimeout(this.sconfig.getSoTimeout());
    if (this.sconfig.getSndBufSize() > 0) {
        socket.setSendBufferSize(this.sconfig.getSndBufSize());
    }
    if (this.sconfig.getRcvBufSize() > 0) {
        socket.setReceiveBufferSize(this.sconfig.getRcvBufSize());
    }
    socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
    final int linger = this.sconfig.getSoLinger();
    if (linger >= 0) {
        socket.setSoLinger(true, linger);
    }
    socket.setKeepAlive(this.sconfig.isSoKeepAlive());
    socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
    return this.connFactory.createConnection(socket);
}
 
Example 15
Project: ProyectoPacientes   File: StandardSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Configures socket properties based on properties from the connection
 * (tcpNoDelay, snd/rcv buf, traffic class, etc).
 * 
 * @param props
 * @throws SocketException
 * @throws IOException
 */
private void configureSocket(Socket sock, Properties props) throws SocketException, IOException {
    sock.setTcpNoDelay(Boolean.valueOf(props.getProperty(TCP_NO_DELAY_PROPERTY_NAME, TCP_NO_DELAY_DEFAULT_VALUE)).booleanValue());

    String keepAlive = props.getProperty(TCP_KEEP_ALIVE_PROPERTY_NAME, TCP_KEEP_ALIVE_DEFAULT_VALUE);

    if (keepAlive != null && keepAlive.length() > 0) {
        sock.setKeepAlive(Boolean.valueOf(keepAlive).booleanValue());
    }

    int receiveBufferSize = Integer.parseInt(props.getProperty(TCP_RCV_BUF_PROPERTY_NAME, TCP_RCV_BUF_DEFAULT_VALUE));

    if (receiveBufferSize > 0) {
        sock.setReceiveBufferSize(receiveBufferSize);
    }

    int sendBufferSize = Integer.parseInt(props.getProperty(TCP_SND_BUF_PROPERTY_NAME, TCP_SND_BUF_DEFAULT_VALUE));

    if (sendBufferSize > 0) {
        sock.setSendBufferSize(sendBufferSize);
    }

    int trafficClass = Integer.parseInt(props.getProperty(TCP_TRAFFIC_CLASS_PROPERTY_NAME, TCP_TRAFFIC_CLASS_DEFAULT_VALUE));

    if (trafficClass > 0) {
        sock.setTrafficClass(trafficClass);
    }
}
 
Example 16
Project: graphouse   File: InsertTest.java   View Source Code Vote up 4 votes
private Socket createSocket() throws IOException {
    Socket socket = new Socket(args.host, args.port);
    socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(args.sendTimeoutSeconds));
    socket.setTcpNoDelay(true);
    return socket;
}
 
Example 17
Project: jdk8u-jdk   File: DnsClient.java   View Source Code Vote up 4 votes
Tcp(InetAddress server, int port) throws IOException {
    sock = new Socket(server, port);
    sock.setTcpNoDelay(true);
    out = new java.io.BufferedOutputStream(sock.getOutputStream());
    in = new java.io.BufferedInputStream(sock.getInputStream());
}
 
Example 18
Project: AndroidDvbDriver   File: TransferThread.java   View Source Code Vote up 4 votes
@Override
public void run() {
    setName(TransferThread.class.getSimpleName());
    setPriority(NORM_PRIORITY);

    OutputStream os = null;
    Socket socket = null;
    try {
        socket = serverSocket.accept();
        socket.setTcpNoDelay(true);

        byte[] buf = new byte[5 * 188];

        os = socket.getOutputStream();

        transportStream = dvbDevice.getTransportStream(new DvbDevice.StreamCallback() {
            @Override
            public void onStreamException(IOException exception) {
                lastException = exception;
                interrupt();
            }

            @Override
            public void onStoppedStreaming() {
                interrupt();
            }
        });
        while (!isInterrupted()) {
            int inlength = transportStream.read(buf);

            if (inlength > 0) {
                os.write(buf, 0, inlength);
            } else {
                // No data, sleep for a bit until available
                quietSleep(10);
            }
        }
    } catch (IOException e) {
        lastException = e;
    } finally {
        quietClose(os);
        quietClose(socket);
        quietClose(transportStream);
        callback.onClosed();
    }
}
 
Example 19
Project: T0rlib4j   File: Utilities.java   View Source Code Vote up 4 votes
public static Socket Socks5connection(Socks5Proxy proxy, String onionUrl, int HiddenServicePort) throws IOException {
    Socket ssock = new SocksSocket(proxy, onionUrl, HiddenServicePort);
    ssock.setTcpNoDelay(true);
    return ssock;

}
 
Example 20
Project: ZooKeeper   File: QuorumCnxManager.java   View Source Code Vote up 2 votes
/**
 * Helper method to set socket options.
 * 
 * @param sock
 *            Reference to socket
 */
private void setSockOpts(Socket sock) throws SocketException {
    sock.setTcpNoDelay(true);
    sock.setSoTimeout(socketTimeout);
}