List of usage examples for io.netty.channel ChannelOption TCP_NODELAY
ChannelOption TCP_NODELAY
To view the source code for io.netty.channel ChannelOption TCP_NODELAY.
Click Source Link
From source file:net.openhft.performance.tests.third.party.frameworks.netty.NettyClientLatencyTest.java
License:Apache License
public static void main(String[] args) throws SSLException, InterruptedException { // Configure SSL.git @Nullable/* www . ja va2 s.co m*/ final SslContext sslCtx; if (SSL) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. @NotNull EventLoopGroup group = new NioEventLoopGroup(); try { @NotNull Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(@NotNull SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new MyChannelInboundHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:net.petercashel.nettyCore.server.serverCore.java
License:Apache License
/** * Initializes the Server listerning socket * * @param port/*from ww w . j ava2s .c o m*/ * - Int port to bind to * @throws Exception */ public static void initializeServer(int port) throws Exception { clientConnectionMap = new HashMap<SocketAddress, ChannelUserHolder>(); AuthTmpUserMap = new HashMap<String, String>(); PacketRegistry.setupRegistry(); PacketRegistry.Side = side; if (UseSSL) SSLContextProvider.SetupSSL(); bossGroup = new NioEventLoopGroup(); // (1) workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("readTimeoutHandler", new ReadTimeoutHandler(300)); if (UseSSL && !SSLContextProvider.selfSigned) p.addLast("ssl", getSSLHandler()); if (UseSSL && SSLContextProvider.selfSigned) p.addLast("ssl", SSLContextProvider.getSelfServer().newHandler(ch.alloc())); p.addLast("InboundOutboundServerHandler", new ServerConnectionHandler()); } }).option(ChannelOption.SO_BACKLOG, 128) // (5) .childOption(ChannelOption.TCP_NODELAY, true); // (6) // Bind and start to accept incoming connections. ChannelFuture f = b.bind("0.0.0.0", port).sync(); // (7) System.out.println("Server Core Initalised!"); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to // gracefully // shut down your server. f.channel().closeFuture().sync(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:net.pms.network.HTTPServer.java
License:Open Source License
public boolean start() throws IOException { hostname = configuration.getServerHostname(); InetSocketAddress address;//ww w.j av a 2s .co m if (StringUtils.isNotBlank(hostname)) { LOGGER.info("Using forced address " + hostname); InetAddress tempIA = InetAddress.getByName(hostname); if (tempIA != null && networkInterface != null && networkInterface.equals(NetworkInterface.getByInetAddress(tempIA))) { address = new InetSocketAddress(tempIA, port); } else { address = new InetSocketAddress(hostname, port); } } else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) { // XXX sets iafinal and networkInterface LOGGER.info("Using address {} found on network interface: {}", iafinal, networkInterface.toString().trim().replace('\n', ' ')); address = new InetSocketAddress(iafinal, port); } else { LOGGER.info("Using localhost address"); address = new InetSocketAddress(port); } LOGGER.info("Created socket: " + address); if (configuration.isHTTPEngineV2()) { // HTTP Engine V2 bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.SO_SNDBUF, 65536).childOption(ChannelOption.SO_RCVBUF, 65536); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(address) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("HttpHandler", new HttpServerCodec()) // eliminate the need to decode http chunks from the client .addLast("aggregator", new HttpObjectAggregator(64 * 1024)) .addLast("chunkedWriter", new ChunkedWriteHandler()) .addLast("handler", new RequestHandlerV2()); } }); try { channel = bootstrap.bind().channel(); } catch (Exception e) { LOGGER.error("Another program is using port " + port + ", which UMS needs."); LOGGER.error("You can change the port UMS uses on the General Configuration tab."); LOGGER.trace("The error was: " + e); PMS.get().getFrame().setStatusCode(0, Messages.getString("PMS.141"), "icon-status-warning.png"); } if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } } else { // HTTP Engine V1 serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); serverSocket.setReuseAddress(true); serverSocket.bind(address); if (hostname == null && iafinal != null) { hostname = iafinal.getHostAddress(); } else if (hostname == null) { hostname = InetAddress.getLocalHost().getHostAddress(); } runnable = new Thread(this, "HTTP Server"); runnable.setDaemon(false); runnable.start(); } return true; }
From source file:net.qing.sms.simulator.NettySmsSimulatorServer.java
License:Apache License
protected void applyConnectionOptions(ServerBootstrap bootstrap) { SocketConfig config = configuration.getSocketConfig(); bootstrap.childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()); if (config.getTcpSendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, config.getTcpSendBufferSize()); }/*w w w .ja v a2 s . c o m*/ if (config.getTcpReceiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, config.getTcpReceiveBufferSize()); } // bootstrap.option(ChannelOption.ALLOCATOR, // PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); // bootstrap.childOption(ChannelOption.ALLOCATOR, // PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()); bootstrap.option(ChannelOption.SO_LINGER, config.getSoLinger()); bootstrap.option(ChannelOption.SO_REUSEADDR, config.isReuseAddress()); bootstrap.option(ChannelOption.SO_BACKLOG, config.getAcceptBackLog()); }
From source file:net.smert.frameworkgl.Network.java
License:Apache License
private void createClient(String host, int port, Supplier<ChannelHandler> channelHandlerSupplier) { // Create event loops clientWorkerGroup = new NioEventLoopGroup(); // Create channel initializer ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() { @Override/* w w w .j av a2s . c o m*/ public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (debug) { p.addLast(new LoggingHandler(logLevel)); } p.addLast(channelHandlerSupplier.get()); } }; // Bootstrap the client client = new Bootstrap(); if (debug) { client.handler(new LoggingHandler(logLevel)); } client.group(clientWorkerGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.TCP_NODELAY, tcpNoDelay) .handler(channelInit); // Connect to the host and port client.connect(host, port); }
From source file:net.smert.frameworkgl.Network.java
License:Apache License
private void createServer(int port, Supplier<ChannelHandler> channelHandlerSupplier) { // Are we already running? if (serverRunning) { return;/*w w w.j av a 2 s . c o m*/ } serverPort = port; // Create event loops serverAcceptGroup = new NioEventLoopGroup(1); serverWorkerGroup = new NioEventLoopGroup(); // Create channel initializer ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (debug) { p.addLast(new LoggingHandler(logLevel)); } p.addLast(channelHandlerSupplier.get()); } }; // Bootstrap the server server = new ServerBootstrap(); if (debug) { server.handler(new LoggingHandler(logLevel)); } server.group(serverAcceptGroup, serverWorkerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, backlog).childHandler(channelInit) .childOption(ChannelOption.SO_KEEPALIVE, keepAlive) .childOption(ChannelOption.TCP_NODELAY, tcpNoDelay); // Start listening on the port server.bind(port); // The server is now running serverRunning = true; }
From source file:net.tomp2p.connection.ChannelCreator.java
License:Apache License
/** * Creates a channel to the given address. This will setup the TCP * connection/*from w w w . ja v a 2 s .c o m*/ * * @param socketAddress * The address to send future messages * @param connectionTimeoutMillis * The timeout for establishing a TCP connection * @param channelHandlers * The handlers to set * @param futureResponse * the futureResponse * @return The channel future object or null if we are shut down. */ public ChannelFuture createTCP(final SocketAddress socketAddress, final int connectionTimeoutMillis, final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers, final FutureResponse futureResponse) { readTCP.lock(); try { if (shutdownTCP) { return null; } if (!semaphoreTCP.tryAcquire()) { LOG.error("Tried to acquire more resources (TCP) than announced!"); throw new RuntimeException("Tried to acquire more resources (TCP) than announced!"); } Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_LINGER, 0); b.option(ChannelOption.SO_REUSEADDR, true); Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers2 = channelClientConfiguration .pipelineFilter().filter(channelHandlers, true, true); addHandlers(b, channelHandlers2); ChannelFuture channelFuture = b.connect(socketAddress, new InetSocketAddress(channelClientConfiguration.senderTCP(), 0)); recipients.add(channelFuture.channel()); setupCloseListener(channelFuture, semaphoreTCP, futureResponse); return channelFuture; } finally { readTCP.unlock(); } }
From source file:net.tomp2p.connection.ChannelServer.java
License:Apache License
/** * Start to listen on a TCP port./* w w w . jav a 2 s. c o m*/ * * @param listenAddresses * The address to listen to * @param config * Can create handlers to be attached to this port * @return True if startup was successful */ boolean startupTCP(final InetSocketAddress listenAddresses, final ChannelServerConfiguration config) { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.config().setAllocator(channelServerConfiguration.byteBufAllocator()); // b.option(ChannelOption.SO_BACKLOG, BACKLOG); bestEffortOptions(ch, ChannelOption.SO_LINGER, 0); bestEffortOptions(ch, ChannelOption.TCP_NODELAY, true); for (Map.Entry<String, Pair<EventExecutorGroup, ChannelHandler>> entry : handlers(true) .entrySet()) { if (!entry.getValue().isEmpty()) { ch.pipeline().addLast(entry.getValue().element0(), entry.getKey(), entry.getValue().element1()); } else if (entry.getValue().element1() != null) { ch.pipeline().addLast(entry.getKey(), entry.getValue().element1()); } } } }); ChannelFuture future = b.bind(listenAddresses); channelsTCP.put(listenAddresses.getAddress(), future.channel()); return handleFuture(future); }
From source file:net.tomp2p.connection2.ChannelCreator.java
License:Apache License
/** * Creates a channel to the given address. This will setup the TCP connection * // w w w . jav a 2s. c om * @param socketAddress * The address to send future messages * @param connectionTimeoutMillis * The timeout for establishing a TCP connection * @param channelHandlers * The handlers to set * @return The channel future object or null if we are shut down. */ public ChannelFuture createTCP(final SocketAddress socketAddress, final int connectionTimeoutMillis, final Map<String, ChannelHandler> channelHandlers) { readTCP.lock(); try { if (shutdownTCP) { return null; } if (!semaphoreTCP.tryAcquire()) { LOG.error("Tried to acquire more resources (TCP) than announced!"); throw new RuntimeException("Tried to acquire more resources (TCP) than announced!"); } Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_LINGER, 0); b.option(ChannelOption.SO_REUSEADDR, true); // b.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE); channelClientConfiguration.pipelineFilter().filter(channelHandlers, true, true); addHandlers(b, channelHandlers); ChannelFuture channelFuture = b.connect(socketAddress); setupCloseListener(channelFuture, semaphoreTCP); CREATED_TCP_CONNECTIONS.incrementAndGet(); return channelFuture; } finally { readTCP.unlock(); } }
From source file:net.tomp2p.connection2.ChannelServer.java
License:Apache License
/** * Start to listen on a TCP port.//from w ww .j av a 2 s.c om * * @param listenAddresses * The address to listen to * @param config * Can create handlers to be attached to this port * @return True if startup was successful */ boolean startupTCP(final InetSocketAddress listenAddresses, final ChannelServerConficuration config) { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { for (Map.Entry<String, ChannelHandler> entry : handlers(true).entrySet()) { ch.pipeline().addLast(entry.getKey(), entry.getValue()); } } }); // b.option(ChannelOption.SO_BACKLOG, BACKLOG); b.childOption(ChannelOption.SO_LINGER, 0); b.childOption(ChannelOption.TCP_NODELAY, true); ChannelFuture future = b.bind(listenAddresses); channelTCP = future.channel(); return handleFuture(future); }