Java Code Examples for java.nio.channels.SocketChannel#setOption()

The following examples show how to use java.nio.channels.SocketChannel#setOption() . 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: SocketChannelStream.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize the SocketStream with a new Socket.
 *
 * @param s the new socket.
 */
public void init(SocketChannel s)
{
  _s = s;

  try {
    s.setOption(StandardSocketOptions.TCP_NODELAY, true);
  } catch (Exception e) {
    e.printStackTrace();;
  }
  //_is = null;
  //_os = null;
  _needsFlush = false;
  
  _readBuffer.clear().flip();
  _writeBuffer.clear();
}
 
Example 2
Source File: TcpCrusherSocketOptions.java    From netcrusher-java with Apache License 2.0 6 votes vote down vote up
void setupSocketChannel(SocketChannel socketChannel) throws IOException {
    socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, keepAlive);
    socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, tcpNoDelay);

    if (rcvBufferSize > 0) {
        socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, rcvBufferSize);
    }

    if (sndBufferSize > 0) {
        socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, sndBufferSize);
    }

    if (lingerMs >= 0) {
        socketChannel.setOption(StandardSocketOptions.SO_LINGER, lingerMs);
    }
}
 
Example 3
Source File: NetSystem.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void setSocketParams(ClosableConnection con, boolean isFrontChannel) throws IOException {
	int sorcvbuf = 0;
    int sosndbuf = 0;
    int soNoDelay = 0;
    
	if (isFrontChannel) {
		sorcvbuf = this.netConfig.getFrontsocketsorcvbuf();
		sosndbuf = this.netConfig.getFrontsocketsosndbuf();
		soNoDelay = this.netConfig.getFrontSocketNoDelay();
	} else {
		sorcvbuf = this.netConfig.getBacksocketsorcvbuf();
		sosndbuf = this.netConfig.getBacksocketsosndbuf();
		soNoDelay = this.netConfig.getBackSocketNoDelay();
	}
	
	SocketChannel socketChannel = con.getSocketChannel();
	socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, sorcvbuf);
	socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, sosndbuf);
	socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, soNoDelay == 1);
    socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
}
 
Example 4
Source File: SimpleSocketServer.java    From antsdb with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void run() {
    try {
        for (;;) {
            SocketChannel channel = this.serverChannel.accept();
            channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
            Orca orca = this.fish.getOrca();
            if (orca == null) {
                channel.close();
                continue;
            }
            if (orca.isClosed()) {
                channel.close();
                continue;
            }
            this.pool.execute(new SimpleSocketWorker(this.fish, channel));
        }
    }
    catch (AsynchronousCloseException ignored) {}
    catch (Exception x) {
        _log.warn("", x);
    }
}
 
Example 5
Source File: FIXAcceptor.java    From parity with Apache License 2.0 6 votes vote down vote up
Session accept() {
    try {
        SocketChannel fix = serverChannel.accept();
        if (fix == null)
            return null;

        try {
            fix.setOption(StandardSocketOptions.TCP_NODELAY, true);
            fix.configureBlocking(false);

            return new Session(orderEntry, fix, config, instruments);
        } catch (IOException e1) {
            fix.close();

            return null;
        }
    } catch (IOException e2) {
        return null;
    }
}
 
Example 6
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_setOption() throws Exception {
    SocketChannel sc = SocketChannel.open();
    sc.setOption(StandardSocketOptions.SO_LINGER, 1000);

    // Assert that we can read back the option from the channel...
    assertEquals(1000, (int) sc.<Integer>getOption(StandardSocketOptions.SO_LINGER));
    // ... and its socket adaptor.
    assertEquals(1000, sc.socket().getSoLinger());

    sc.close();
    try {
        sc.setOption(StandardSocketOptions.SO_LINGER, 2000);
        fail();
    } catch (ClosedChannelException expected) {
    }
}
 
Example 7
Source File: SocketSettings.java    From datakernel with Apache License 2.0 6 votes vote down vote up
public void applySettings(@NotNull SocketChannel channel) throws IOException {
	if (sendBufferSize != 0) {
		channel.setOption(SO_SNDBUF, sendBufferSize);
	}
	if (receiveBufferSize != 0) {
		channel.setOption(SO_RCVBUF, receiveBufferSize);
	}
	if (keepAlive != DEF_BOOL) {
		channel.setOption(SO_KEEPALIVE, keepAlive != FALSE);
	}
	if (reuseAddress != DEF_BOOL) {
		channel.setOption(SO_REUSEADDR, reuseAddress != FALSE);
	}
	if (tcpNoDelay != DEF_BOOL) {
		channel.setOption(TCP_NODELAY, tcpNoDelay != FALSE);
	}
}
 
Example 8
Source File: OrderEntryFactory.java    From parity with Apache License 2.0 5 votes vote down vote up
SoupBinTCPClient create(POEClientListener listener,
        SoupBinTCPClientStatusListener statusListener) throws IOException {
    SocketChannel channel = SocketChannel.open();

    channel.connect(address);

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.configureBlocking(false);

    return new SoupBinTCPClient(channel, POE.MAX_OUTBOUND_MESSAGE_LENGTH,
            new POEClientParser(listener), statusListener);
}
 
Example 9
Source File: Server.java    From nassau with Apache License 2.0 5 votes vote down vote up
public Session accept() throws IOException {
    SocketChannel channel = serverChannel.accept();
    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.configureBlocking(false);

    return new Session(channel);
}
 
Example 10
Source File: TestClient.java    From nassau with Apache License 2.0 5 votes vote down vote up
private static TestClient connect(SocketAddress address) throws IOException {
    SocketChannel channel = SocketChannel.open();

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.connect(address);
    channel.configureBlocking(false);

    return new TestClient(channel);
}
 
Example 11
Source File: DownstreamServer.java    From nassau with Apache License 2.0 5 votes vote down vote up
public Session accept() throws IOException {
    SocketChannel downstream = serverChannel.accept();
    if (downstream == null)
        return null;

    downstream.setOption(StandardSocketOptions.TCP_NODELAY, true);
    downstream.configureBlocking(false);

    return new Session(upstream, downstream);
}
 
Example 12
Source File: EchoServerOld.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void accept(SelectionKey key) throws IOException {
    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

    SocketChannel socketChannel = serverSocketChannel.accept();
    socketChannel.configureBlocking(false);
    socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
    socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    socketChannel.register(selector, SelectionKey.OP_READ);

    System.out.println("Client is connected");
}
 
Example 13
Source File: PingPongWithMains.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
private void testClient() throws IOException {

        SocketChannel sc = TCPRegistry.createSocketChannel(serverHostPort);
        sc.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        sc.configureBlocking(false);

        //       testThroughput(sc);
        testLatency(serverHostPort, WireType.BINARY, sc);

        TcpChannelHub.closeAllHubs();
        TCPRegistry.reset();
    }
 
Example 14
Source File: Initiator.java    From philadelphia with Apache License 2.0 5 votes vote down vote up
static Initiator open(SocketAddress address) throws IOException {
    SocketChannel channel = SocketChannel.open();

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.connect(address);
    channel.configureBlocking(false);

    return new Initiator(channel);
}
 
Example 15
Source File: Acceptor.java    From philadelphia with Apache License 2.0 5 votes vote down vote up
Session accept() throws IOException {
    SocketChannel channel = serverChannel.accept();

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.configureBlocking(false);

    return new Session(channel);
}
 
Example 16
Source File: DefaultTcpChannelSupplier.java    From artio with Apache License 2.0 5 votes vote down vote up
private void configure(final SocketChannel channel) throws IOException
{
    channel.setOption(TCP_NODELAY, true);
    if (configuration.receiverSocketBufferSize() > 0)
    {
        channel.setOption(SO_RCVBUF, configuration.receiverSocketBufferSize());
    }
    if (configuration.senderSocketBufferSize() > 0)
    {
        channel.setOption(SO_SNDBUF, configuration.senderSocketBufferSize());
    }
}
 
Example 17
Source File: AbstractBenchmarkClient.java    From artio with Apache License 2.0 5 votes vote down vote up
protected SocketChannel open() throws IOException
{
    final SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
    socketChannel.configureBlocking(false);
    socketChannel.setOption(TCP_NODELAY, true);
    socketChannel.setOption(SO_RCVBUF, 1024 * 1024);
    socketChannel.setOption(SO_RCVBUF, 1024 * 1024);
    return socketChannel;
}
 
Example 18
Source File: OrderEntry.java    From parity-extras with Apache License 2.0 5 votes vote down vote up
public static OrderEntry open(InetSocketAddress address) throws IOException {
    SocketChannel channel = SocketChannel.open();

    channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
    channel.connect(address);
    channel.configureBlocking(false);

    MessageListener listener = new POEClientParser(new Listener());

    SoupBinTCPClient transport = new SoupBinTCPClient(channel, POE.MAX_OUTBOUND_MESSAGE_LENGTH,
            listener, new StatusListener());

    return new OrderEntry(transport);
}
 
Example 19
Source File: ConnectionFactory.java    From Mycat-NIO with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Connection make(SocketChannel channel) throws IOException {
	channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
	// 子类完成具体连接创建工作
	Connection c = makeConnection(channel);
	// 设置连接的参数
	NetSystem.getInstance().setSocketParams(c,true);
	// 设置NIOHandler
	c.setHandler(getNIOHandler());
	return c;
}
 
Example 20
Source File: NetworkHandler.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * Processes an OP_ACCEPT selection event
 *
 * We will accept the connection if we haven't reached the maximum number of
 * connections. The new socket channel will be placed in non-blocking mode
 * and the selection key enabled for read events. We will not add the peer
 * address to the peer address list since we only want nodes that have
 * advertised their availability on the list.
 */
private void processAccept(SelectionKey acceptKey) {
	try {
		SocketChannel channel = listenChannel.accept();
		if (channel != null) {
			InetSocketAddress remoteAddress = (InetSocketAddress) channel.getRemoteAddress();
			PeerAddress address = new PeerAddress(remoteAddress);
			if (connections.size() >= maxConnections) {
				channel.close();
				BTCLoader.info(String.format("Max connections reached: Connection rejected from %s", address));
			} else if (isBlacklisted(address.getAddress())) {
				channel.close();
				BTCLoader.info(String.format("Connection rejected from banned address %s", address));
			} else if (connectionMap.get(address.getAddress()) != null) {
				channel.close();
				BTCLoader.info(String.format("Duplicate connection rejected from %s", address));
			} else {
				address.setTimeConnected(System.currentTimeMillis() / 1000);
				channel.configureBlocking(false);
				channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
				SelectionKey key = channel.register(networkSelector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
				Peer peer = new Peer(address, channel, key);
				key.attach(peer);
				peer.setConnected(true);
				address.setConnected(true);
				BTCLoader.info(String.format("Connection accepted from %s", address));
				Message msg = VersionMessage.buildVersionMessage(peer, BTCLoader.listenAddress,
						BTCLoader.blockStore.getChainHeight());
				synchronized (connections) {
					connections.add(peer);
					connectionMap.put(address.getAddress(), peer);
					peer.getOutputList().add(msg);
				}
				BTCLoader.info(String.format("Sent 'version' message to %s", address));
			}
		}
	} catch (IOException exc) {
		BTCLoader.error("Unable to accept connection", exc);
		networkShutdown = true;
	}
}