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

The following examples show how to use java.net.Socket#setTcpNoDelay() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RawTCPLatencyTest.java    From nats.java with Apache License 2.0 6 votes vote down vote up
private static void runServer() throws IOException {
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("Connected");
            socket.setTcpNoDelay(true);
            socket.setReceiveBufferSize(2 * 1024 * 1024);
            socket.setSendBufferSize(2 * 1024 * 1024);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            try {
                while (true) {
                    int rq = in.read();
                    out.write(rq);
                }
            } catch (IOException e) {
                System.out.println("Disconnected");
            }
        }
    }
}
 
Example 2
Source File: UtilsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getSocketOptions() throws Exception {
  Socket socket = new Socket();
  socket.setSoLinger(true, 2);
  socket.setSoTimeout(3);
  socket.setTcpNoDelay(true);
  socket.setReuseAddress(true);
  socket.setReceiveBufferSize(4000);
  socket.setSendBufferSize(5000);
  socket.setKeepAlive(true);
  socket.setOOBInline(true);
  socket.setTrafficClass(8); // note: see javadoc for valid input values

  SocketOptions socketOptions = Utils.getSocketOptions(socket);
  assertEquals(2, (int) socketOptions.lingerSeconds);
  assertEquals(3, (int) socketOptions.soTimeoutMillis);
  assertEquals("true", socketOptions.others.get("TCP_NODELAY"));
  assertEquals("true", socketOptions.others.get("SO_REUSEADDR"));
  assertEquals("4000", socketOptions.others.get("SO_RECVBUF"));
  assertEquals("5000", socketOptions.others.get("SO_SNDBUF"));
  assertEquals("true", socketOptions.others.get("SO_KEEPALIVE"));
  assertEquals("true", socketOptions.others.get("SO_OOBINLINE"));
  assertEquals("8", socketOptions.others.get("IP_TOS"));
}
 
Example 3
Source File: MllpClientResource.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
public void connect(int connectTimeout) {
    try {
        clientSocket = new Socket();

        clientSocket.connect(new InetSocketAddress(mllpHost, mllpPort), connectTimeout);

        clientSocket.setSoTimeout(soTimeout);
        clientSocket.setSoLinger(false, -1);
        clientSocket.setReuseAddress(reuseAddress);
        clientSocket.setTcpNoDelay(tcpNoDelay);

        inputStream = clientSocket.getInputStream();
        outputStream = new BufferedOutputStream(clientSocket.getOutputStream(), 2048);
    } catch (IOException e) {
        String errorMessage = String.format("Unable to establish connection to %s:%s", mllpHost, mllpPort);
        log.error(errorMessage, e);
        throw new MllpJUnitResourceException(errorMessage, e);
    }
}
 
Example 4
Source File: GfxdTSSLSocket.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the socket properties like timeout, keepalive, buffer sizes.
 * 
 * @param timeout
 *          Milliseconds timeout
 * @param params
 *          Socket parameters including buffer sizes and keep-alive settings
 * @param props
 *          the system properties instance to use and initialize global socket
 *          options like keepalive and buffer sizes that are not set in params
 */
protected void setProperties(Socket socket, int timeout,
    SocketParameters params, SystemProperties props)
    throws TTransportException {
  this.inputBufferSize = params.getInputBufferSize(props
      .getSocketInputBufferSize());
  this.outputBufferSize = params.getOutputBufferSize(props
      .getSocketOutputBufferSize());
  try {
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    this.timeout = GfxdTSocket.setTimeout(socket, timeout, params, props);
  } catch (SocketException se) {
    LOGGER.warn("Could not set socket timeout.", se);
    throw new TTransportException(TTransportException.NOT_OPEN,
        "Could not set socket timeout.", se);
  }
}
 
Example 5
Source File: NioLaserClient.java    From laser with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取并配置SocketChannel
 *
 * @return 返回SocketChannel
 * @throws IOException
 */
private SocketChannel getAndConfigSocketChannel() throws IOException {
    final SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    // config the socket
    final Socket socket = socketChannel.socket();
    socket.setTcpNoDelay(options.isClientTcpNoDelay());
    socket.setReceiveBufferSize(options.getClientSocketReceiverBufferSize());
    socket.setSendBufferSize(options.getClientSocketSendBufferSize());
    socket.setSoTimeout(options.getClientSocketTimeout());
    socket.setPerformancePreferences(
            options.getClientPerformancePreferences()[0],
            options.getClientPerformancePreferences()[1],
            options.getClientPerformancePreferences()[2]);
    socket.setTrafficClass(options.getClientTrafficClass());
    return socketChannel;
}
 
Example 6
Source File: BenchServer.java    From jocket with Apache License 2.0 5 votes vote down vote up
private void initWithSocket() throws IOException {
  ServerSocket srv = new ServerSocket(PORT);
  System.out.println("Java ServerSocket listening on " + srv.getLocalPort());
  Socket s = srv.accept();
  srv.close();
  s.setTcpNoDelay(true);
  run(new DataInputStream(s.getInputStream()), s.getOutputStream());
}
 
Example 7
Source File: DefaultSocketFactoryImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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 8
Source File: VerySimpleClient.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
@NotNull
private SocketChannel createClient(EventLoop eg, String desc) throws Exception {

    Exception e = null;
    for (int i = 0; i < 10; i++) {

        SocketChannel result = null;
        try {

            result = TCPRegistry.createSocketChannel(desc);
            if (result == null)
                continue;
            int tcpBufferSize = 2 << 20;
            Socket socket = result.socket();
            socket.setTcpNoDelay(true);
            socket.setReceiveBufferSize(tcpBufferSize);
            socket.setSendBufferSize(tcpBufferSize);
            result.configureBlocking(false);
            return result;

        } catch (IOException e0) {
            e = e0;
            continue;
        }
    }

    throw e;
}
 
Example 9
Source File: DefaultSocketFactoryImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: NioLaserServer.java    From laser with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 配置SocketChannel
 *
 * @throws IOException
 */
private void configSocketChannel(SocketChannel socketChannel) throws IOException {
    socketChannel.configureBlocking(false);
    // config the socket
    final Socket socket = socketChannel.socket();
    socket.setTcpNoDelay(options.isServerChildTcpNoDelay());
    socket.setReceiveBufferSize(options.getServerChildSocketReceiverBufferSize());
    socket.setSendBufferSize(options.getServerChildSocketSendBufferSize());
    socket.setSoTimeout(options.getServerChildSocketTimeout());
    socket.setPerformancePreferences(
            options.getServerChildPerformancePreferences()[0],
            options.getServerChildPerformancePreferences()[1],
            options.getServerChildPerformancePreferences()[2]);
    socket.setTrafficClass(options.getServerChildTrafficClass());
}
 
Example 11
Source File: ConnectionThread.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param socket
 *            The socket for the connection.
 * @param dataStore
 *            The storage for all the data implementing the datamodel
 *            interface.
 */
public ConnectionThread(final int clientID, final Socket socket,
		final DataModel dataStore, final BufferServer buffer) {
	this.clientID = clientID;
	this.socket = socket;
	this.dataStore = dataStore;
	try {
		 socket.setTcpNoDelay(true); // disable Nagle's algorithm... i.e. allow small packets
	} catch ( SocketException e ) {
		 System.err.println("Failed to set socket option TCP_NODELAY");
	}
	clientAdress = socket.getInetAddress().toString() + ":"
			+ Integer.toString(socket.getPort());
	this.buffer = buffer;
}
 
Example 12
Source File: CommonWireIOTestCase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 13
Source File: TcpConnection.java    From kryonet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void connect (Selector selector, SocketAddress remoteAddress, int timeout) throws IOException {
	close();
	writeBuffer.clear();
	readBuffer.clear();
	readBuffer.flip();
	currentObjectLength = 0;
	try {
		SocketChannel socketChannel = selector.provider().openSocketChannel();
		Socket socket = socketChannel.socket();
		socket.setTcpNoDelay(true);
		// socket.setTrafficClass(IPTOS_LOWDELAY);
		socket.connect(remoteAddress, timeout); // Connect using blocking mode for simplicity.
		socketChannel.configureBlocking(false);
		this.socketChannel = socketChannel;

		selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);
		selectionKey.attach(this);

		if (DEBUG) {
			debug("kryonet", "Port " + socketChannel.socket().getLocalPort() + "/TCP connected to: "
				+ socketChannel.socket().getRemoteSocketAddress());
		}

		lastReadTime = lastWriteTime = System.currentTimeMillis();
	} catch (IOException ex) {
		close();
		IOException ioEx = new IOException("Unable to connect to: " + remoteAddress);
		ioEx.initCause(ex);
		throw ioEx;
	}
}
 
Example 14
Source File: SocketChannel.java    From TeamSpeak-3-Java-API with MIT License 5 votes vote down vote up
SocketChannel(TS3Config config) throws IOException {
	try {
		socket = new Socket(config.getHost(), config.getQueryPort());
		socket.setTcpNoDelay(true);
		socket.setSoTimeout(config.getCommandTimeout());
	} catch (IOException ioe) {
		close();
		throw ioe;
	}
}
 
Example 15
Source File: TNonblockingSocket.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private TNonblockingSocket(SocketChannel socketChannel, int timeout, SocketAddress socketAddress)
    throws IOException {
  socketChannel_ = socketChannel;
  socketAddress_ = socketAddress;

  // make it a nonblocking channel
  socketChannel.configureBlocking(false);

  // set options
  Socket socket = socketChannel.socket();
  socket.setSoLinger(false, 0);
  socket.setTcpNoDelay(true);
  setTimeout(timeout);
}
 
Example 16
Source File: RpcSocketHelper.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
/**
 * Configure a socket with specified properties.
 */
public static void configureSocket(Socket socket, Properties properties) {
	if (socket == null || properties == null) {
		return;
	}

	try {
		// Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
		boolean tcpNoDelay = RpcPropertyDefs.getPropertyAsBoolean(properties,
				RpcPropertyDefs.RPC_SOCKET_TCP_NO_DELAY_NICK,
				RpcPropertyDefs.RPC_SOCKET_TCP_NO_DELAY_DEFAULT);
		socket.setTcpNoDelay(tcpNoDelay);
		
		String keepAlive = RpcPropertyDefs.getProperty(properties,
				RpcPropertyDefs.RPC_SOCKET_USE_KEEPALIVE_NICK);

		int timeouts = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK,
				RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_DEFAULT);

		int[] perfPrefs = RpcPropertyDefs.getPropertyAsIntArray(properties,
				RpcPropertyDefs.RPC_SOCKET_PERFORMANCE_PREFERENCES_NICK,
				RpcPropertyDefs.RPC_DEFAULT_PROPERTY_DELIMITER,
				RpcPropertyDefs.RPC_SOCKET_PERFORMANCE_PREFERENCES_DEFAULT);

		// Setting the socket performance preferences, described by three
		// integers whose values indicate the relative importance of short
		// connection time, low latency, and high bandwidth.
		// Socket.setPerformancePreferences(int connectionTime, int latency, int bandwidth)
		// The default values is (1, 2, 0), assume no one changes them.
		// This gives the highest importance to low latency, followed by
		// short connection time, and least importance to high bandwidth.
		if (perfPrefs != null && perfPrefs.length == 3) {
			socket.setPerformancePreferences(
					perfPrefs[0],
					perfPrefs[1],
					perfPrefs[2]);
		}
		
		socket.setSoTimeout(timeouts);

		if ((keepAlive != null)
				&& (keepAlive.startsWith("n") || keepAlive.startsWith("N"))) {
			socket.setKeepAlive(false);
		} else {
			socket.setKeepAlive(true);
		}

		int sockRecvBufSize = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_RECV_BUF_SIZE_NICK, 0);
		int sockSendBufSize = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_SEND_BUF_SIZE_NICK, 0);

		if (sockRecvBufSize != 0) {
			socket.setReceiveBufferSize(sockRecvBufSize);
		}

		if (sockSendBufSize != 0) {
			socket.setSendBufferSize(sockSendBufSize);
		}
	} catch (Throwable exc) {
		Log
				.warn("Unexpected exception while setting Perforce RPC socket options: "
						+ exc.getLocalizedMessage());
		Log.exception(exc);
	}
}
 
Example 17
Source File: DnsClient.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
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
Source File: DnsClient.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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 19
Source File: RpcSocketHelper.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
/**
 * Configure a socket with specified properties.
 */
public static void configureSocket(Socket socket, Properties properties) {
	if (socket == null || properties == null) {
		return;
	}

	try {
		// Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
		boolean tcpNoDelay = RpcPropertyDefs.getPropertyAsBoolean(properties,
				RpcPropertyDefs.RPC_SOCKET_TCP_NO_DELAY_NICK,
				RpcPropertyDefs.RPC_SOCKET_TCP_NO_DELAY_DEFAULT);
		socket.setTcpNoDelay(tcpNoDelay);
		
		String keepAlive = RpcPropertyDefs.getProperty(properties,
				RpcPropertyDefs.RPC_SOCKET_USE_KEEPALIVE_NICK);

		int timeouts = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK,
				RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_DEFAULT);

		int[] perfPrefs = RpcPropertyDefs.getPropertyAsIntArray(properties,
				RpcPropertyDefs.RPC_SOCKET_PERFORMANCE_PREFERENCES_NICK,
				RpcPropertyDefs.RPC_DEFAULT_PROPERTY_DELIMITER,
				RpcPropertyDefs.RPC_SOCKET_PERFORMANCE_PREFERENCES_DEFAULT);

		// Setting the socket performance preferences, described by three
		// integers whose values indicate the relative importance of short
		// connection time, low latency, and high bandwidth.
		// Socket.setPerformancePreferences(int connectionTime, int latency, int bandwidth)
		// The default values is (1, 2, 0), assume no one changes them.
		// This gives the highest importance to low latency, followed by
		// short connection time, and least importance to high bandwidth.
		if (perfPrefs != null && perfPrefs.length == 3) {
			socket.setPerformancePreferences(
					perfPrefs[0],
					perfPrefs[1],
					perfPrefs[2]);
		}
		
		socket.setSoTimeout(timeouts);

		if ((keepAlive != null)
				&& (keepAlive.startsWith("n") || keepAlive.startsWith("N"))) {
			socket.setKeepAlive(false);
		} else {
			socket.setKeepAlive(true);
		}

		int sockRecvBufSize = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_RECV_BUF_SIZE_NICK, 0);
		int sockSendBufSize = RpcPropertyDefs.getPropertyAsInt(properties,
				RpcPropertyDefs.RPC_SOCKET_SEND_BUF_SIZE_NICK, 0);

		if (sockRecvBufSize != 0) {
			socket.setReceiveBufferSize(sockRecvBufSize);
		}

		if (sockSendBufSize != 0) {
			socket.setSendBufferSize(sockSendBufSize);
		}
	} catch (Throwable exc) {
		Log
				.warn("Unexpected exception while setting Perforce RPC socket options: "
						+ exc.getLocalizedMessage());
		Log.exception(exc);
	}
}
 
Example 20
Source File: PeerManager.java    From jelectrum with MIT License 4 votes vote down vote up
private boolean checkPeerInternal(PeerInfo peer)
  throws Exception
{
    peer.updateAddress();

    Socket sock = openSocket(peer);
    sock.setTcpNoDelay(true);
    sock.setSoTimeout(15000);

    Scanner scan = new Scanner(sock.getInputStream());
    PrintStream out = new PrintStream(sock.getOutputStream());

    int height_to_check = Math.max(0, jelly.getElectrumNotifier().getHeadHeight() - 2);

    Sha256Hash block_hash = jelly.getBlockChainCache().getBlockHashAtHeight(height_to_check);
    StoredBlock blk = jelly.getDB().getBlockStoreMap().get(block_hash);
    JSONObject my_result = new JSONObject();
    jelly.getElectrumNotifier().populateBlockData(blk, my_result);

    String my_header = my_result.getString("hex");

    String header_string = getRecentBlockHeader(out, scan, height_to_check);

    if (!my_header.equals(header_string))
    {
      throw new Exception(String.format("Header string mismatch - %d  Expected: %s, got %s", height_to_check, my_header, header_string));
    }
    //System.out.println("Header match on " + height_to_check);


    JSONObject serverfeatures = getServerFeatures(out, scan);

    String hash = serverfeatures.getString("genesis_hash");
    if(!genesis_hash.equals(hash))
    {
      throw new Exception("Genesis hash: Expected " + genesis_hash + " got " + hash);
    }
    peer.protocol_max = serverfeatures.getString("protocol_max");
    peer.protocol_min = serverfeatures.getString("protocol_min");
    peer.server_version = serverfeatures.getString("server_version");
    if (serverfeatures.isNull("pruning")) peer.pruning = 0;
    else
    {
      peer.pruning = serverfeatures.getInt("pruning");
    }
    addRemotePeers(out, scan);
    addSelfToPeer(out, scan);

    sock.close();

    return true;

}