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

The following examples show how to use java.net.Socket#setSendBufferSize() . 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: SocketProperties.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
public void setProperties(Socket socket) throws SocketException{
    if (rxBufSize != null)
        socket.setReceiveBufferSize(rxBufSize.intValue());
    if (txBufSize != null)
        socket.setSendBufferSize(txBufSize.intValue());
    if (ooBInline !=null)
        socket.setOOBInline(ooBInline.booleanValue());
    if (soKeepAlive != null)
        socket.setKeepAlive(soKeepAlive.booleanValue());
    if (performanceConnectionTime != null && performanceLatency != null &&
            performanceBandwidth != null)
        socket.setPerformancePreferences(
                performanceConnectionTime.intValue(),
                performanceLatency.intValue(),
                performanceBandwidth.intValue());
    if (soReuseAddress != null)
        socket.setReuseAddress(soReuseAddress.booleanValue());
    if (soLingerOn != null && soLingerTime != null)
        socket.setSoLinger(soLingerOn.booleanValue(),
                soLingerTime.intValue());
    if (soTimeout != null && soTimeout.intValue() >= 0)
        socket.setSoTimeout(soTimeout.intValue());
    if (tcpNoDelay != null)
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
 
Example 2
Source File: RequestListener.java    From java-android-websocket-client with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        while (!isTerminated() && !Thread.interrupted()) {
            final Socket socket = this.serversocket.accept();
            socket.setSoTimeout(this.socketConfig.getSoTimeout());
            socket.setKeepAlive(this.socketConfig.isSoKeepAlive());
            socket.setTcpNoDelay(this.socketConfig.isTcpNoDelay());
            if (this.socketConfig.getRcvBufSize() > 0) {
                socket.setReceiveBufferSize(this.socketConfig.getRcvBufSize());
            }
            if (this.socketConfig.getSndBufSize() > 0) {
                socket.setSendBufferSize(this.socketConfig.getSndBufSize());
            }
            if (this.socketConfig.getSoLinger() >= 0) {
                socket.setSoLinger(true, this.socketConfig.getSoLinger());
            }
            final HttpServerConnection conn = this.connectionFactory.createConnection(socket);
            final Worker worker = new Worker(this.httpService, conn, this.exceptionLogger);
            this.executorService.execute(worker);
        }
    } catch (final Exception ex) {
        this.exceptionLogger.log(ex);
    }
}
 
Example 3
Source File: RawTCPLatencyTest.java    From nats.java with Apache License 2.0 6 votes vote down vote up
private static void runClient() throws SocketException, IOException {
    Socket socket = new Socket();
    socket.setTcpNoDelay(true);
    socket.setReceiveBufferSize(2 * 1024 * 1024);
    socket.setSendBufferSize(2 * 1024 * 1024);
    socket.connect(new InetSocketAddress(host, port), 1000);
    in = socket.getInputStream();
    out = socket.getOutputStream();
    System.out.println("Connected");
    for (int i = 0; i < warmIters; i++) {
        sendRecv();
    }
    System.out.println("Warmed");
    long t0 = System.nanoTime();
    for (int i = 0; i < runIters; i++) {
        sendRecv();
    }
    long t1 = System.nanoTime();
    System.out.println("Average latency " + (1.0 * (t1 - t0)) / (1000000.0 * runIters) + " ms");
    socket.close();
}
 
Example 4
Source File: SocketFactoryImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the current settings to the given socket.
 *
 * @param s Socket to apply the settings to
 * @return Socket the input socket
 */
protected Socket applySettings(Socket s) {
  try {
    s.setKeepAlive(SO_KEEPALIVE);
    s.setOOBInline(OOBINLINE);
    s.setReuseAddress(SO_REUSEADDR);
    s.setTcpNoDelay(TCP_NODELAY);
    s.setOOBInline(OOBINLINE);

    s.setReceiveBufferSize(SO_RCVBUF);
    s.setSendBufferSize(SO_SNDBUF);
    s.setSoTimeout(SO_TIMEOUT);
    s.setSoLinger(SO_LINGER, LINGER);
  } catch (SocketException e) {
    throw new RuntimeException(e);
  }
  return s;
}
 
Example 5
Source File: BlockingChannel.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and connects a Socket
 * @return Socket
 * @throws IOException
 */
public Socket createSocket() throws IOException {
  Socket tcpSocket = new Socket();

  if (readBufferSize > 0) {
    tcpSocket.setReceiveBufferSize(readBufferSize);
  }
  if (writeBufferSize > 0) {
    tcpSocket.setSendBufferSize(writeBufferSize);
  }
  tcpSocket.setSoTimeout(readTimeoutMs);
  tcpSocket.setKeepAlive(true);
  tcpSocket.setTcpNoDelay(enableTcpNoDelay);
  tcpSocket.connect(new InetSocketAddress(host, port), connectTimeoutMs);

  logger.debug("Created socket with SO_TIMEOUT = {} (requested {}), "
          + "SO_RCVBUF = {} (requested {}), SO_SNDBUF = {} (requested {})", tcpSocket.getSoTimeout(), readTimeoutMs,
      tcpSocket.getReceiveBufferSize(), readBufferSize, tcpSocket.getSendBufferSize(), writeBufferSize);

  return tcpSocket;
}
 
Example 6
Source File: DFSOutputStream.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Create a socket for a write pipeline
 * @param first the first datanode 
 * @param length the pipeline length
 * @param client client
 * @return the socket connected to the first datanode
 */
static Socket createSocketForPipeline(final DatanodeInfo first,
    final int length, final DFSClient client) throws IOException {
  final String dnAddr = first.getXferAddr(
      client.getConf().connectToDnViaHostname);
  if (DFSClient.LOG.isDebugEnabled()) {
    DFSClient.LOG.debug("Connecting to datanode " + dnAddr);
  }
  final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr);
  final Socket sock = client.socketFactory.createSocket();
  final int timeout = client.getDatanodeReadTimeout(length);
  NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), client.getConf().socketTimeout);
  sock.setSoTimeout(timeout);
  sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);
  if(DFSClient.LOG.isDebugEnabled()) {
    DFSClient.LOG.debug("Send buf size " + sock.getSendBufferSize());
  }
  return sock;
}
 
Example 7
Source File: RemoteOutputBlockStreamHandle.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Override
public OutputBlockStream openBlockStream() throws IOException {

	Socket socket = connect();
	socket.setSendBufferSize(getPreferredBufferSize());

	return new ClientOutputBlockStream(socket);
}
 
Example 8
Source File: StandardSocketFactory.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 9
Source File: PhysicalConnection.java    From ClickHouse-Native-JDBC with Apache License 2.0 5 votes vote down vote up
public static PhysicalConnection openPhysicalConnection(ClickHouseConfig configure) throws SQLException {
    try {
        SocketAddress endpoint = new InetSocketAddress(configure.address(), configure.port());

        Socket socket = new Socket();
        socket.setTcpNoDelay(true);
        socket.setSendBufferSize(ClickHouseDefines.SOCKET_BUFFER_SIZE);
        socket.setReceiveBufferSize(ClickHouseDefines.SOCKET_BUFFER_SIZE);
        socket.connect(endpoint, configure.connectTimeout());

        return new PhysicalConnection(socket, new BinarySerializer(new SocketBuffedWriter(socket), true), new BinaryDeserializer(socket));
    } catch (IOException ex) {
        throw new SQLException(ex.getMessage(), ex);
    }
}
 
Example 10
Source File: BioSender.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: FrontendConnectionFactory.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
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 12
Source File: MockTcpTransport.java    From crate with Apache License 2.0 5 votes vote down vote up
private void configureSocket(Socket socket) throws SocketException {
    socket.setTcpNoDelay(TransportSettings.TCP_NO_DELAY.get(settings));
    ByteSizeValue tcpSendBufferSize = TransportSettings.TCP_SEND_BUFFER_SIZE.get(settings);
    if (tcpSendBufferSize.getBytes() > 0) {
        socket.setSendBufferSize(tcpSendBufferSize.bytesAsInt());
    }
    ByteSizeValue tcpReceiveBufferSize = TransportSettings.TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.getBytes() > 0) {
        socket.setReceiveBufferSize(tcpReceiveBufferSize.bytesAsInt());
    }
    socket.setReuseAddress(TransportSettings.TCP_REUSE_ADDRESS.get(settings));
}
 
Example 13
Source File: RestClient.java    From Doradus with Apache License 2.0 5 votes vote down vote up
public void connect(String host, int port)
throws Exception
{
    disconnect();

    m_host = host;
    m_port = port;

    m_socket = new Socket();
    if (m_socket == null) {
        throw new Exception("Failed to create socket");
    }

    try  {
        if (DISABLE_NAGLES) {
            m_socket.setTcpNoDelay(true);
        }
        if (USE_CUSTOM_BUFFER_SIZE) {
            if (m_socket.getSendBufferSize() < NET_BUFFER_SIZE) {
                m_socket.setSendBufferSize(NET_BUFFER_SIZE);
            }
            if (m_socket.getReceiveBufferSize() < NET_BUFFER_SIZE) {
                m_socket.setReceiveBufferSize(NET_BUFFER_SIZE);
            }
        }

        SocketAddress addr = new InetSocketAddress(m_host, m_port);
        m_socket.connect(addr);

        m_inStream  = new BufferedInputStream(m_socket.getInputStream(), NET_BUFFER_SIZE);
        m_outStream = new BufferedOutputStream(m_socket.getOutputStream(), NET_BUFFER_SIZE);
    }
    catch(Exception ex) {
        disconnect();
        String msg = "Failed to connect to " + m_host + ":" + m_port;
        throw new Exception(msg, ex);
    }
}
 
Example 14
Source File: BioReceiver.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void listen() throws Exception {
    if (doListen()) {
        log.warn(sm.getString("bioReceiver.already.started"));
        return;
    }
    setListen(true);

    while ( doListen() ) {
        Socket socket = null;
        if ( getTaskPool().available() < 1 ) {
            if ( log.isWarnEnabled() )
                log.warn(sm.getString("bioReceiver.threads.busy"));
        }
        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 15
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 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: TcpListener.java    From Mycat-Balance with Apache License 2.0 4 votes vote down vote up
@Override
public void run()
{
	synchronized (channelContext)
	{
		try
		{

			log.debug("start buildlink for {}", channelContext.getId());

			SocketChannel socketChannel = SocketChannel.open();
			
			
			// String xx = socketChannel.toString();
			bind(channelContext, socketChannel); // 绑定ip
			
	

			if (channelContext.getProxy() == null)
			{
				try
				{
					socketChannel.connect(socketAddress);
				} catch (IOException e)
				{
					log.error(
							channelContext.getBindIp() + ":" + channelContext.getBindPort() + "---"
									+ e.getLocalizedMessage(), e);
					socketChannel.close();
					throw e;
				}
				socketChannel.configureBlocking(false); // 非阻塞,此行不能少,否则IllegalBlockingModeException
			} else
			// 使用代理
			{
				socketChannel.connect(channelContext.getProxy().address());
				socketChannel.configureBlocking(false); // 非阻塞,此行不能少,否则IllegalBlockingModeException
				NioProxy.proxyImpl(socketChannel, socketAddress);
			}
			
			
			

			Socket socket = socketChannel.socket();
			socket.setSendBufferSize(1048576); // 262142
			socket.setReceiveBufferSize(1048576);

			channelContext.setMyIp(socketChannel.socket().getLocalAddress().getHostAddress());
			channelContext.setMyPort(socketChannel.socket().getLocalPort());
			channelContext.generateId();
			
			// int logIndex = 1;
			// log.warn("" + logIndex++);

			// CommunicateManager.getMapOfSocketChannelAndsocketChannelId().put(socketChannel,
			// channelContext.getsocketChannelId());
			mapOfSocketChannelAndChannelContext.put(socketChannel, channelContext);
			channelContext.setSocketChannel(socketChannel);
			channelContext.getStatVo().setStateTimeTcpBuilding(SystemTimer.currentTimeMillis());
			channelContext.setDesc4Err("");
			

			SendUtils.resumeCount(channelContext);

			socketChannel.register(socketMsgListener.selector, SelectionKey.OP_READ, socketMsgListener); // 注册到selector中去
			
			
			
			
			socketMsgListener.selector.wakeup();
			log.info("{} socket connection has been built, waiting app connection ", channelContext.getId());
			channelContext.setConnectionState(ConnectionState.TCP_ON);
			
			
			
			
		} catch (Exception t)
		{
			log.error("occured when build link " + channelContext.getId(), t);
			channelContext.getStatVo().getBuildExceptionTimes().incrementAndGet();
			channelContext.setConnectionState(ConnectionState.TCP_LINKFAILED);
			channelContext.setDesc4Err(t.getMessage());

		} finally
		{
			// skip it
		}
	}
	
}
 
Example 18
Source File: AbstractConnectProtocol.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static Socket createSocket(final String host, final int port, final Options options)
    throws SQLException {
  Socket socket;
  try {
    socket = Utils.createSocket(options, host);
    socket.setTcpNoDelay(options.tcpNoDelay);

    if (options.socketTimeout != null) {
      socket.setSoTimeout(options.socketTimeout);
    }
    if (options.tcpKeepAlive) {
      socket.setKeepAlive(true);
    }
    if (options.tcpRcvBuf != null) {
      socket.setReceiveBufferSize(options.tcpRcvBuf);
    }
    if (options.tcpSndBuf != null) {
      socket.setSendBufferSize(options.tcpSndBuf);
    }
    if (options.tcpAbortiveClose) {
      socket.setSoLinger(true, 0);
    }

    // Bind the socket to a particular interface if the connection property
    // localSocketAddress has been defined.
    if (options.localSocketAddress != null) {
      InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
      socket.bind(localAddress);
    }

    if (!socket.isConnected()) {
      InetSocketAddress sockAddr =
          options.pipe == null ? new InetSocketAddress(host, port) : null;
      socket.connect(sockAddr, options.connectTimeout);
    }
    return socket;

  } catch (IOException ioe) {
    throw ExceptionFactory.INSTANCE.create(
        String.format(
            "Socket fail to connect to host:%s, port:%s. %s", host, port, ioe.getMessage()),
        "08000",
        ioe);
  }
}
 
Example 19
Source File: IncomingSocketChannelManager.java    From BiglyBT with GNU General Public License v2.0 2 votes vote down vote up
protected void
 process(
int						local_port,
TransportHelperFilter 	filter )

 {

   SocketChannel	channel = ((TCPTransportHelper)filter.getHelper()).getSocketChannel();

   Socket socket = channel.socket();

   //set advanced socket options
   try {
     int so_sndbuf_size = COConfigurationManager.getIntParameter( "network.tcp.socket.SO_SNDBUF" );
     if( so_sndbuf_size > 0 )  socket.setSendBufferSize( so_sndbuf_size );

     String ip_tos = COConfigurationManager.getStringParameter( "network.tcp.socket.IPDiffServ" );
     if( ip_tos.length() > 0 )  socket.setTrafficClass( Integer.decode( ip_tos ).intValue() );
   }
   catch( Throwable t ) {
     t.printStackTrace();
   }

   AEProxyAddressMapper.AppliedPortMapping applied_mapping = proxy_address_mapper.applyPortMapping( socket.getInetAddress(), socket.getPort());

   InetSocketAddress	tcp_address = applied_mapping.getRemoteAddress();

ConnectionEndpoint	co_ep = new ConnectionEndpoint(tcp_address);

Map<String,Object>	properties = applied_mapping.getProperties();

if ( properties != null ){

	co_ep.addProperties( properties );
}

ProtocolEndpointTCP	pe_tcp = (ProtocolEndpointTCP)ProtocolEndpointFactory.createEndpoint( ProtocolEndpoint.PROTOCOL_TCP, co_ep, tcp_address );

Transport transport = new TCPTransportImpl( pe_tcp, filter );

   incoming_manager.addConnection( local_port, filter, transport );
 }
 
Example 20
Source File: IncomingSocketChannelManager.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
protected void 
 process( 
int						local_port, 
TransportHelperFilter 	filter )

 {

   SocketChannel	channel = ((TCPTransportHelper)filter.getHelper()).getSocketChannel();
      
   Socket socket = channel.socket();

   //set advanced socket options
   try {
     int so_sndbuf_size = COConfigurationManager.getIntParameter( "network.tcp.socket.SO_SNDBUF" );
     if( so_sndbuf_size > 0 )  socket.setSendBufferSize( so_sndbuf_size );
     
     String ip_tos = COConfigurationManager.getStringParameter( "network.tcp.socket.IPDiffServ" );
     if( ip_tos.length() > 0 )  socket.setTrafficClass( Integer.decode( ip_tos ).intValue() );
   }
   catch( Throwable t ) {
     t.printStackTrace();
   }
   
   AEProxyAddressMapper.AppliedPortMapping applied_mapping = proxy_address_mapper.applyPortMapping( socket.getInetAddress(), socket.getPort());
   
   InetSocketAddress	tcp_address = applied_mapping.getAddress();
   
ConnectionEndpoint	co_ep = new ConnectionEndpoint(tcp_address);

Map<String,Object>	properties = applied_mapping.getProperties();

if ( properties != null ){
	
	co_ep.addProperties( properties );
}

ProtocolEndpointTCP	pe_tcp = (ProtocolEndpointTCP)ProtocolEndpointFactory.createEndpoint( ProtocolEndpoint.PROTOCOL_TCP, co_ep, tcp_address );

Transport transport = new TCPTransportImpl( pe_tcp, filter );

   incoming_manager.addConnection( local_port, filter, transport );
 }