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

The following examples show how to use java.net.Socket#setReceiveBufferSize() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
public SetReceiveBufferSize() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    Socket s = new Socket("localhost", ss.getLocalPort());
    Socket accepted = ss.accept();
    try {
        s.setReceiveBufferSize(0);
    } catch (IllegalArgumentException e) {
        return;
    } catch (Exception ex) {
    } finally {
        ss.close();
        s.close();
        accepted.close();
    }
    throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
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
Source Project: lucene-solr   File: SocketProxy.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  try {
    while (!socket.isClosed()) {
      pause.get().await();
      try {
        Socket source = socket.accept();
        pause.get().await();
        if (receiveBufferSize > 0) {
          source.setReceiveBufferSize(receiveBufferSize);
        }
        if (log.isInfoEnabled()) {
          log.info("accepted {}, receiveBufferSize: {}", source, source.getReceiveBufferSize());
        }
        synchronized (connections) {
          connections.add(new Bridge(source, target));
        }
      } catch (SocketTimeoutException expected) {}
    }
  } catch (Exception e) {
    if (log.isDebugEnabled()) {
      log.debug("acceptor: finished for reason: {}", e.getLocalizedMessage());
    }
  }
}
 
Example 4
/**
 * 获取并配置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 5
public SetReceiveBufferSize() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    Socket s = new Socket("localhost", ss.getLocalPort());
    Socket accepted = ss.accept();
    try {
        s.setReceiveBufferSize(0);
    } catch (IllegalArgumentException e) {
        return;
    } catch (Exception ex) {
    } finally {
        ss.close();
        s.close();
        accepted.close();
    }
    throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
Example 6
public SetReceiveBufferSize() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    Socket s = new Socket("localhost", ss.getLocalPort());
    Socket accepted = ss.accept();
    try {
        s.setReceiveBufferSize(0);
    } catch (IllegalArgumentException e) {
        return;
    } catch (Exception ex) {
    } finally {
        ss.close();
        s.close();
        accepted.close();
    }
    throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
Example 7
Source Project: nats.java   File: RawTCPLatencyTest.java    License: 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 8
Source Project: ignite   File: TcpClientChannel.java    License: Apache License 2.0 6 votes vote down vote up
/** Create socket. */
private static Socket createSocket(ClientChannelConfiguration cfg) throws IOException {
    Socket sock = cfg.getSslMode() == SslMode.REQUIRED ?
        new ClientSslSocketFactory(cfg).create() :
        new Socket(cfg.getAddress().getHostName(), cfg.getAddress().getPort());

    sock.setTcpNoDelay(cfg.isTcpNoDelay());

    if (cfg.getTimeout() > 0)
        sock.setSoTimeout(cfg.getTimeout());

    if (cfg.getSendBufferSize() > 0)
        sock.setSendBufferSize(cfg.getSendBufferSize());

    if (cfg.getReceiveBufferSize() > 0)
        sock.setReceiveBufferSize(cfg.getReceiveBufferSize());

    return sock;
}
 
Example 9
Source Project: Tomcat8-Source-Read   File: BioReceiver.java    License: 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 10
Source Project: Tomcat8-Source-Read   File: BioSender.java    License: MIT License 5 votes vote down vote up
/**
 * Open real socket and set time out when waitForAck is enabled
 * is socket open return directly.
 * @throws IOException Error opening socket
 */
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("bioSender.openSocket", getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)));
  } catch (IOException ex1) {
      SenderState.getSenderState(getDestination()).setSuspect();
      if (log.isDebugEnabled())
          log.debug(sm.getString("bioSender.openSocket.failure",getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
      throw ex1;
    }

 }
 
Example 11
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 Project: logging-log4j2   File: SocketOptions.java    License: Apache License 2.0 5 votes vote down vote up
public void apply(final Socket socket) throws SocketException {
    if (keepAlive != null) {
        socket.setKeepAlive(keepAlive.booleanValue());
    }
    if (oobInline != null) {
        socket.setOOBInline(oobInline.booleanValue());
    }
    if (reuseAddress != null) {
        socket.setReuseAddress(reuseAddress.booleanValue());
    }
    if (performancePreferences != null) {
        performancePreferences.apply(socket);
    }
    if (receiveBufferSize != null) {
        socket.setReceiveBufferSize(receiveBufferSize.intValue());
    }
    if (soLinger != null) {
        socket.setSoLinger(true, soLinger.intValue());
    }
    if (soTimeout != null) {
        socket.setSoTimeout(soTimeout.intValue());
    }
    if (tcpNoDelay != null) {
        socket.setTcpNoDelay(tcpNoDelay.booleanValue());
    }
    final Integer actualTrafficClass = getActualTrafficClass();
    if (actualTrafficClass != null) {
        socket.setTrafficClass(actualTrafficClass);
    }
}
 
Example 13
@Override
void serveBlockStream(Socket socket, BlockStream blockStream) throws IOException {

	if (!(blockStream instanceof OutputBlockStream)) {
		throw new IllegalArgumentException("expected OutputBlockStream");
	}

	socket.setReceiveBufferSize(getPreferredBufferSize());

	OutputBlockStream outputBlockStream = (OutputBlockStream) blockStream;
	try (InputStream in = socket.getInputStream()) {

		copyBlockData(outputBlockStream, in);

		// perform final handshake (uncompressed)

		readStreamEnd(socket, true);

		// Need to close blockStream while client is waiting for final stream end 
		// indicator. This is needed so that the server-based file is fully written 
		// before the client is let loose from the handshake
		outputBlockStream.close();

		writeStreamEnd(socket);
	}
	catch (SocketException e) {
		// remain silent if socket closed by client (e.g., cancelled)
		if (e.getMessage().startsWith("Broken pipe")) {
			throw new EOFException("unexpected end of stream");
		}
		throw e;
	}

}
 
Example 14
Source Project: imhotep   File: ImhotepRemoteSession.java    License: Apache License 2.0 5 votes vote down vote up
private static Socket newSocket(String host, int port, int timeout) throws IOException {
    final Socket socket = new Socket(host, port);
    socket.setReceiveBufferSize(65536);
    socket.setSoTimeout(timeout >= 0 ? timeout : DEFAULT_SOCKET_TIMEOUT);
    socket.setTcpNoDelay(true);
    return socket;
}
 
Example 15
Source Project: jlibs   File: TCPConnection.java    License: Apache License 2.0 5 votes vote down vote up
protected void init() throws IOException{
    uniqueID = (server==null ? "C" : "A")+id;
    Socket socket = selectable.socket();
    if(TCP_NODELAY!=null)
        socket.setTcpNoDelay(TCP_NODELAY);
    if(SO_LINGER!=null)
        socket.setSoLinger(SO_LINGER<0, SO_LINGER);
    if(SO_SNDBUF!=null)
        socket.setSendBufferSize(SO_SNDBUF);
    if(SO_RCVBUF!=null)
        socket.setReceiveBufferSize(SO_RCVBUF);
}
 
Example 16
/**
 * 配置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 17
Source Project: j2objc   File: SocketChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testSocket_setOptions() throws IOException {
    channel1.connect(localAddr1);
    Socket socket = channel1.socket();

    ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3});
    socket.setKeepAlive(true);
    channel1.write(buffer);

    socket.setOOBInline(true);
    channel1.write(buffer);

    socket.setReceiveBufferSize(100);
    channel1.write(buffer);

    socket.setReuseAddress(true);
    channel1.write(buffer);

    socket.setSendBufferSize(100);
    channel1.write(buffer);

    socket.setSoLinger(true, 100);
    channel1.write(buffer);

    socket.setSoTimeout(1000);
    channel1.write(buffer);

    socket.setTcpNoDelay(true);
    channel1.write(buffer);

    socket.setTrafficClass(10);
    channel1.write(buffer);
}
 
Example 18
Source Project: crate   File: MockTcpTransport.java    License: 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 19
Source Project: Mycat-Balance   File: TcpListener.java    License: 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 20
/**
 * Creates a socket and connects it to the given host for a data transfer
 * channel. Socket timeouts are automatically set according to the values of
 * {@link FTPConnector#connectionTimeout}, {@link FTPConnector#readTimeout}
 * and {@link FTPConnector#closeTimeout}.
 * 
 * If you are extending FTPConnector, consider using this method to
 * establish your socket connection for the communication channel, instead
 * of creating Socket objects, since it is already aware of the timeout
 * values possibly given by the caller.
 * 
 * @param host
 *            The host for the connection.
 * @param port
 *            The port for the connection.
 * @return The connected socket.
 * @throws IOException
 *             If connection fails.
 * @since 1.7
 */
protected Socket tcpConnectForDataTransferChannel(String host, int port) throws IOException {
	Socket socket = new Socket();
	socket.setSoTimeout(readTimeout * 1000);
	socket.setSoLinger(true, closeTimeout);
	socket.setReceiveBufferSize(512 * 1024);
	socket.setSendBufferSize(512 * 1024);
	socket.connect(new InetSocketAddress(host, port), connectionTimeout * 1000);
	return socket;
}