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

The following examples show how to use java.net.Socket#setKeepAlive() . These examples are extracted from open source projects. 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 Project: grpc-nebula-java   File: UtilsTest.java    License: 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 2
private void configureSocket(Socket socket, SocketConfig socketConfig) throws IOException {
  socket.setSoTimeout(socketConfig.getSoTimeout());
  socket.setReuseAddress(socketConfig.isSoReuseAddress());
  socket.setTcpNoDelay(socketConfig.isTcpNoDelay());
  socket.setKeepAlive(socketConfig.isSoKeepAlive());

  if (socketConfig.getRcvBufSize() > 0) {
    socket.setReceiveBufferSize(socketConfig.getRcvBufSize());
  }

  if (socketConfig.getSndBufSize() > 0) {
    socket.setSendBufferSize(socketConfig.getSndBufSize());
  }

  if (socketConfig.getSoLinger() >= 0) {
    socket.setSoLinger(true, socketConfig.getSoLinger());
  }
}
 
Example 3
/**
 * Opens this <tt>TCPMasterConnection</tt>.
 *
 * @throws Exception if there is a network failure.
 */
@Override
public synchronized boolean connect() throws Exception {
    if (!isConnected()) {
        logger.debug("connect()");
        m_Socket = new Socket();
        m_Socket.connect(new InetSocketAddress(m_Address, m_Port), this.m_ConnectTimeoutMillis);
        setTimeout(m_Timeout);
        m_Socket.setReuseAddress(true);
        m_Socket.setSoLinger(true, 1);
        m_Socket.setKeepAlive(true);
        prepareTransport();
        m_Connected = true;
    }
    return m_Connected;
}
 
Example 4
Source Project: grpc-java   File: UtilsTest.java    License: 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 5
/**
 * 连接bash.
 * @param ip 宿主机ip地址
 * @param execId 命令id
 * @return 连接的socket
 * @throws IOException
 */
private Socket connectExec(String ip, String execId) throws IOException {
    Socket socket=new Socket(ip,2375);
    socket.setKeepAlive(true);
    OutputStream out = socket.getOutputStream();
    StringBuffer pw = new StringBuffer();
    pw.append("POST /exec/"+execId+"/start HTTP/1.1\r\n");
    pw.append("Host: "+ip+":2375\r\n");
    pw.append("User-Agent: Docker-Client\r\n");
    pw.append("Content-Type: application/json\r\n");
    pw.append("Connection: Upgrade\r\n");
    JSONObject obj = new JSONObject();
    obj.put("Detach",false);
    obj.put("Tty",true);
    String json=obj.toJSONString();
    pw.append("Content-Length: "+json.length()+"\r\n");
    pw.append("Upgrade: tcp\r\n");
    pw.append("\r\n");
    pw.append(json);
    out.write(pw.toString().getBytes("UTF-8"));
    out.flush();
    return socket;
}
 
Example 6
Source Project: gemfirexd-oss   File: Connection.java    License: Apache License 2.0 5 votes vote down vote up
/** creates a connection that we accepted (it was initiated by
   * an explicit connect being done on the other side).
   */
  private Connection(ConnectionTable t, Socket s)
    throws IOException, ConnectionException
  {
    if (t == null) {
      throw new IllegalArgumentException(LocalizedStrings.Connection_NULL_CONNECTIONTABLE.toLocalizedString());
    }
    this.isReceiver = true;
    this.owner = t;
    this.logger = owner.getLogger();
    Assert.assertTrue(this.logger != null);
    this.socket = s;
    this.conduitIdStr = owner.getConduit().getId().toString();
    this.handshakeRead = false;
    this.handshakeCancelled = false;
    this.connected = true;

    try {
      s.setTcpNoDelay(true);
      s.setKeepAlive(true);
//      s.setSoLinger(true, (Integer.valueOf(System.getProperty("p2p.lingerTime", "5000"))).intValue());
      setSendBufferSize(s, SMALL_BUFFER_SIZE);
      setReceiveBufferSize(s);
    }
    catch (SocketException e) {
      // unable to get the settings we want.  Don't log an error because it will
      // likely happen a lot
    }
    if (!useNIO()) {
      try {
        //this.output = new BufferedOutputStream(s.getOutputStream(), SMALL_BUFFER_SIZE);
        this.output = s.getOutputStream();
      }
      catch (IOException io) {
        logger.severe(LocalizedStrings.Connection_UNABLE_TO_GET_P2P_CONNECTION_STREAMS, io);
        SocketCreator.asyncClose(s, this.logger, this.remoteAddr.toString(), null);
        throw io;
      }
    }
  }
 
Example 7
Source Project: nettythrift   File: DemoClientTEST.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_tcp_shortMsgAndProxy() throws Exception {
	Socket socket = new Socket();
	try {
		// configSocket(socket);
		// socket.connect(new InetSocketAddress("10.50.0.174", 8081), 6000);
		socket.connect(new InetSocketAddress("localhost", 8083), 6000);
		socket.setReuseAddress(true);
		socket.setSoLinger(false, 0);
		socket.setTcpNoDelay(true);
		socket.setKeepAlive(false);
		// socket.setSoTimeout(5000);
		/**
		 * 发送TCP请求
		 */
		OutputStream out = socket.getOutputStream();
		String proxy = "PROXY TCP4 198.51.100.22 203.0.113.7 35646 80\r\n";
		// out.write((proxy + getPingBao).getBytes());
		out.write((proxy + PING).getBytes());
		out.flush();
		System.out.println("==== 响应 ========");
		System.out.println(new String(read(socket.getInputStream())));
	} finally {
		System.out.println("关闭socket");
		socket.close();
	}
}
 
Example 8
Source Project: crate   File: BlobIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHeadRequestConnectionIsNotClosed() throws Exception {
    Socket socket = new Socket(randomNode.getAddress(), randomNode.getPort());
    socket.setKeepAlive(true);
    socket.setSoTimeout(3000);

    OutputStream outputStream = socket.getOutputStream();
    outputStream.write("HEAD /_blobs/invalid/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1\r\n"
        .getBytes(StandardCharsets.UTF_8));
    outputStream.write("Host: localhost\r\n\r\n".getBytes(StandardCharsets.UTF_8));
    outputStream.flush();

    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
    int linesRead = 0;
    while (linesRead < 3) {
        String line = reader.readLine();
        System.out.println(line);
        linesRead++;
    }

    assertSocketIsConnected(socket);
    outputStream.write("HEAD /_blobs/invalid/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1\r\n"
        .getBytes(StandardCharsets.UTF_8));
    outputStream.write("Host: localhost\r\n\r\n".getBytes(StandardCharsets.UTF_8));
    outputStream.flush();
    int read = reader.read();
    assertThat(read, greaterThan(-1));
    assertSocketIsConnected(socket);
}
 
Example 9
Source Project: gemfirexd-oss   File: Connection.java    License: Apache License 2.0 5 votes vote down vote up
/** creates a connection that we accepted (it was initiated by
   * an explicit connect being done on the other side).
   */
  private Connection(ConnectionTable t, Socket s)
    throws IOException, ConnectionException
  {
    if (t == null) {
      throw new IllegalArgumentException(LocalizedStrings.Connection_NULL_CONNECTIONTABLE.toLocalizedString());
    }
    this.isReceiver = true;
    this.owner = t;
    this.logger = owner.getLogger();
    Assert.assertTrue(this.logger != null);
    this.socket = s;
    this.conduitIdStr = owner.getConduit().getId().toString();
    this.handshakeRead = false;
    this.handshakeCancelled = false;
    this.connected = true;

    try {
      s.setTcpNoDelay(true);
      s.setKeepAlive(true);
//      s.setSoLinger(true, (Integer.valueOf(System.getProperty("p2p.lingerTime", "5000"))).intValue());
      setSendBufferSize(s, SMALL_BUFFER_SIZE);
      setReceiveBufferSize(s);
    }
    catch (SocketException e) {
      // unable to get the settings we want.  Don't log an error because it will
      // likely happen a lot
    }
    if (!useNIO()) {
      try {
        //this.output = new BufferedOutputStream(s.getOutputStream(), SMALL_BUFFER_SIZE);
        this.output = s.getOutputStream();
      }
      catch (IOException io) {
        logger.severe(LocalizedStrings.Connection_UNABLE_TO_GET_P2P_CONNECTION_STREAMS, io);
        SocketCreator.asyncClose(s, this.logger, this.remoteAddr.toString(), null);
        throw io;
      }
    }
  }
 
Example 10
Source Project: canal   File: BioSocketChannelPool.java    License: Apache License 2.0 5 votes vote down vote up
public static BioSocketChannel open(SocketAddress address) throws Exception {
    Socket socket = new Socket();
    socket.setSoTimeout(BioSocketChannel.SO_TIMEOUT);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReuseAddress(true);
    socket.connect(address, BioSocketChannel.DEFAULT_CONNECT_TIMEOUT);
    return new BioSocketChannel(socket);
}
 
Example 11
Source Project: AndServer   File: ProxyHandler.java    License: Apache License 2.0 5 votes vote down vote up
private Socket createSocket(HttpHost host) throws IOException {
    Socket socket = new Socket();
    socket.setSoTimeout(60 * 1000);
    socket.setReuseAddress(true);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setReceiveBufferSize(BUFFER);
    socket.setSendBufferSize(BUFFER);
    socket.setSoLinger(true, 0);

    String scheme = host.getSchemeName();
    String hostName = host.getHostName();
    int port = host.getPort();

    InetSocketAddress address = resolveAddress(scheme, hostName, port);
    socket.connect(address, 10 * 1000);

    if ("https".equalsIgnoreCase(scheme)) {
        SSLSocket sslSocket = (SSLSocket) mSocketFactory.createSocket(socket, hostName, port, true);
        try {
            sslSocket.startHandshake();
            final SSLSession session = sslSocket.getSession();
            if (session == null) {
                throw new SSLHandshakeException("SSL session not available.");
            }
        } catch (final IOException ex) {
            IOUtils.closeQuietly(sslSocket);
            throw ex;
        }
        return sslSocket;
    }
    return socket;
}
 
Example 12
public FrontendConnection make(SocketChannel channel) throws IOException {
    Socket socket = channel.socket();
    socket.setReceiveBufferSize(socketRecvBuffer);
    socket.setSendBufferSize(socketSendBuffer);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    FrontendConnection c = getConnection(channel);
    c.setPacketHeaderSize(packetHeaderSize);
    c.setMaxPacketSize(maxPacketSize);
    c.setWriteQueue(new BufferQueue(writeQueueCapcity));
    c.setIdleTimeout(idleTimeout);
    c.setCharset(charset);
    return c;
}
 
Example 13
Source Project: tomcatsrc   File: BioReceiver.java    License: Apache License 2.0 5 votes vote down vote up
public void listen() throws Exception {
    if (doListen()) {
        log.warn("ServerSocket already started");
        return;
    }
    setListen(true);

    while ( doListen() ) {
        Socket socket = null;
        if ( getTaskPool().available() < 1 ) {
            if ( log.isWarnEnabled() )
                log.warn("All BIO server replication threads are busy, unable to handle more requests until a thread is freed up.");
        }
        BioReplicationTask task = (BioReplicationTask)getTaskPool().getRxTask();
        if ( task == null ) continue; //should never happen
        try {
            socket = serverSocket.accept();
        }catch ( Exception x ) {
            if ( doListen() ) throw x;
        }
        if ( !doListen() ) {
            task.setDoRun(false);
            task.serviceSocket(null,null);
            getExecutor().execute(task);
            break; //regular shutdown
        }
        if ( socket == null ) continue;
        socket.setReceiveBufferSize(getRxBufSize());
        socket.setSendBufferSize(getTxBufSize());
        socket.setTcpNoDelay(getTcpNoDelay());
        socket.setKeepAlive(getSoKeepAlive());
        socket.setOOBInline(getOoBInline());
        socket.setReuseAddress(getSoReuseAddress());
        socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
        socket.setSoTimeout(getTimeout());
        ObjectReader reader = new ObjectReader(socket);
        task.serviceSocket(socket,reader);
        getExecutor().execute(task);
    }//while
}
 
Example 14
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 15
Source Project: drift   File: ApacheThriftMethodInvoker.java    License: Apache License 2.0 5 votes vote down vote up
private void setSocketProperties(Socket socket)
        throws SocketException
{
    socket.setSoLinger(false, 0);
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    socket.setSoTimeout(Ints.saturatedCast(requestTimeoutMillis));
}
 
Example 16
Source Project: mts   File: Config.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void getConfigForTCPSocket(Socket socket, boolean tlsTransport) throws Exception
  {
boolean keepAlive = Config.getConfigByName("tcp.properties").getBoolean("socket.KEEP_ALIVE", false);
socket.setKeepAlive(keepAlive);
if (!tlsTransport)
{
	boolean oobInline = Config.getConfigByName("tcp.properties").getBoolean("socket.OOB_INLINE", false);
	socket.setOOBInline(oobInline);
}
int receiveBuffer = Config.getConfigByName("tcp.properties").getInteger("socket.RECEIVE_BUFFER", 8192);
socket.setReceiveBufferSize(receiveBuffer);
boolean reuseAddress = Config.getConfigByName("tcp.properties").getBoolean("socket.REUSE_ADDRESS", false);
socket.setReuseAddress(reuseAddress);
int sendBuffer = Config.getConfigByName("tcp.properties").getInteger("socket.SEND_BUFFER", 8192);
socket.setSendBufferSize(sendBuffer);
int lingerTimeout = Config.getConfigByName("tcp.properties").getInteger("socket.LINGER_TIMEOUT", -1);
if (lingerTimeout >= 0)
	socket.setSoLinger(true, lingerTimeout);
else
	socket.setSoLinger(false, 0);
int timeout = Config.getConfigByName("tcp.properties").getInteger("socket.TIMEOUT", 0);
socket.setSoTimeout(timeout);
boolean tcpNoDelay = Config.getConfigByName("tcp.properties").getBoolean("socket.TCP_NO_DELAY", false);
socket.setTcpNoDelay(tcpNoDelay);
int trafficClass = Config.getConfigByName("tcp.properties").getInteger("socket.TRAFFIC_CLASS", 0);
socket.setTrafficClass(trafficClass);
  }
 
Example 17
Source Project: p4ic4idea   File: RpcSocketHelper.java    License: 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 18
Source Project: java-tcp-tunnel   File: TCPTunnel.java    License: MIT License 4 votes vote down vote up
/**
 * Connects to the remote host and starts bidirectional forwarding (the tunnel).
 */
public void run() {
  String dateStr = sdf.format(new Date());
  try {
    // Connect to the destination server
    serverSocket = new Socket(params.getRemoteHost(), params.getRemotePort());

    // Turn on keep-alive for both the sockets
    serverSocket.setKeepAlive(true);
    localSocket.setKeepAlive(true);

    // Obtain client & server input & output streams
    InputStream clientIn = localSocket.getInputStream();
    OutputStream clientOut = localSocket.getOutputStream();
    InputStream serverIn = serverSocket.getInputStream();
    OutputStream serverOut = serverSocket.getOutputStream();

    // Start forwarding data between server and client
    active = true;
    String clientAddr = toStr(localSocket);
    String serverAddr = toStr(serverSocket);
    String hummanClientAddr = Utils.mapAddrToHumanReadable(clientAddr);
    String hummanServerAddr = Utils.mapAddrToHumanReadable(serverAddr);
    clientAddr = clientAddr+" ("+hummanClientAddr+")";
    serverAddr = serverAddr+" ("+hummanServerAddr+")";
    TCPForwarder clientForward = new TCPForwarder(this, clientIn, serverOut, params, true, clientAddr);
    clientForward.start();
    TCPForwarder serverForward = new TCPForwarder(this, serverIn, clientOut, params, false, serverAddr);
    serverForward.start();

    if (params.isPrint()) {
      System.out.println(dateStr+": TCP Forwarding " + clientAddr + " <--> " + serverAddr);
    }
  } catch (IOException ioe) {
    if (params.isPrint()) {
      String remoteAddr = params.getRemoteHost() + ":" + params.getRemotePort();
      String humanRemoteAddr = Utils.mapAddrToHumanReadable(remoteAddr);
      remoteAddr = remoteAddr + " ("+humanRemoteAddr+")";
      System.err.println(dateStr + ": Failed to connect to remote host (" + remoteAddr + ")");
    }
    connectionBroken();
  }
}
 
Example 19
Source Project: p4ic4idea   File: RpcSocketHelper.java    License: 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 Project: balzac   File: ServerSocketDaemon.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return a Socket for this daemon. The socket is creating using
 * {@code InetAddress.getLocalHost()} as host.
 * 
 * @return a socket.
 * @throws IOException if an I/O error occurs when creating the socket.
 */
public Socket getSocket() throws IOException {
    Socket socket = new Socket(InetAddress.getLocalHost(), getPort());
    socket.setKeepAlive(true);
    return socket;
}