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:com.trinity.engine.protocol.detail.TrinityConnectionManager.java
License:Apache License
/** * Initialise the connection manager context * * @param configuration the configuration on which all connection executes *///from w w w .j a v a 2 s . c o m public void initialise(Protocol configuration) { mProtocol = configuration; mBootstrap.group(mBossGroup, mWorkerGroup).channel(NioServerSocketChannel.class) .childHandler(new ConnectionChannel(mProtocol.getLookupService(), this)) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); }
From source file:com.turn.ttorrent.client.io.PeerClient.java
License:Apache License
public void start() throws Exception { bootstrap = new Bootstrap(); bootstrap.group(environment.getEventService()); bootstrap.channel(environment.getEventLoopType().getClientChannelType()); // SocketAddress address = environment.getLocalPeerListenAddress(); // if (address != null) bootstrap.localAddress(address); bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); // bootstrap.option(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(10)); // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE // bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024); // bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); }
From source file:com.turn.ttorrent.client.io.PeerServer.java
License:Apache License
/** * Create and start a new listening service for our torrents, reporting * with our peer ID on the given address. * * <p>/*from w w w .jav a2s .c o m*/ * This binds to the first available port in the client port range * PORT_RANGE_START to PORT_RANGE_END. * </p> */ public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(environment.getEventService()); bootstrap.channel(environment.getEventLoopType().getServerChannelType()); bootstrap.option(ChannelOption.SO_BACKLOG, 128); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents)); } }); bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES)); // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024); // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024); SocketAddress address = environment.getLocalPeerListenAddress(); if (address != null) { future = bootstrap.bind(address).sync(); } else { BIND: { Exception x = new IOException("No available port for the BitTorrent client!"); for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) { try { future = bootstrap.bind(i).sync(); break BIND; } catch (InterruptedException e) { throw e; } catch (Exception e) { x = e; } } throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + "," + PORT_RANGE_END + "]", x); } } }
From source file:com.turo.pushy.apns.ApnsChannelFactory.java
License:Open Source License
ApnsChannelFactory(final SslContext sslContext, final ApnsSigningKey signingKey, final ProxyHandlerFactory proxyHandlerFactory, final int connectTimeoutMillis, final long idlePingIntervalMillis, final long gracefulShutdownTimeoutMillis, final Http2FrameLogger frameLogger, final InetSocketAddress apnsServerAddress, final EventLoopGroup eventLoopGroup) { this.sslContext = sslContext; if (this.sslContext instanceof ReferenceCounted) { ((ReferenceCounted) this.sslContext).retain(); }//from w w w . j a v a 2 s. c o m this.addressResolverGroup = proxyHandlerFactory == null ? new RoundRobinDnsAddressResolverGroup( ClientChannelClassUtil.getDatagramChannelClass(eventLoopGroup), DefaultDnsServerAddressStreamProvider.INSTANCE) : NoopAddressResolverGroup.INSTANCE; this.bootstrapTemplate = new Bootstrap(); this.bootstrapTemplate.group(eventLoopGroup); this.bootstrapTemplate.option(ChannelOption.TCP_NODELAY, true); this.bootstrapTemplate.remoteAddress(apnsServerAddress); this.bootstrapTemplate.resolver(this.addressResolverGroup); if (connectTimeoutMillis > 0) { this.bootstrapTemplate.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMillis); } this.bootstrapTemplate.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) { final ChannelPipeline pipeline = channel.pipeline(); if (proxyHandlerFactory != null) { pipeline.addFirst(proxyHandlerFactory.createProxyHandler()); } final SslHandler sslHandler = sslContext.newHandler(channel.alloc()); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> handshakeFuture) { if (handshakeFuture.isSuccess()) { final String authority = channel.remoteAddress().getHostName(); final ApnsClientHandler.ApnsClientHandlerBuilder clientHandlerBuilder; if (signingKey != null) { clientHandlerBuilder = new TokenAuthenticationApnsClientHandler.TokenAuthenticationApnsClientHandlerBuilder() .signingKey(signingKey).authority(authority) .idlePingIntervalMillis(idlePingIntervalMillis); } else { clientHandlerBuilder = new ApnsClientHandler.ApnsClientHandlerBuilder() .authority(authority).idlePingIntervalMillis(idlePingIntervalMillis); } if (frameLogger != null) { clientHandlerBuilder.frameLogger(frameLogger); } final ApnsClientHandler apnsClientHandler = clientHandlerBuilder.build(); if (gracefulShutdownTimeoutMillis > 0) { apnsClientHandler.gracefulShutdownTimeoutMillis(gracefulShutdownTimeoutMillis); } // TODO Use a named constant when https://github.com/netty/netty/pull/8683 is available pipeline.addLast(new FlushConsolidationHandler(256, true)); pipeline.addLast( new IdleStateHandler(idlePingIntervalMillis, 0, 0, TimeUnit.MILLISECONDS)); pipeline.addLast(apnsClientHandler); pipeline.remove(ConnectionNegotiationErrorHandler.INSTANCE); channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get().trySuccess(channel); } else { tryFailureAndLogRejectedCause(channel.attr(CHANNEL_READY_PROMISE_ATTRIBUTE_KEY).get(), handshakeFuture.cause()); } } }); pipeline.addLast(sslHandler); pipeline.addLast(ConnectionNegotiationErrorHandler.INSTANCE); } }); }
From source file:com.twocater.diamond.core.netty.NettyConnector.java
@Override public void bind() throws Exception { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup); ChannelHandlerAdapter serverHandler = this.nettyHandlerFactory.createServerHandler(); if (serverHandler != null) { serverBootstrap.handler(serverHandler); }//w ww . j ava 2 s . c o m serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(this.nettyHandlerFactory.createChildHandler(connectorConfig.getTimeout())); serverBootstrap.option(ChannelOption.SO_BACKLOG, connectorConfig.getSo_backlog_parent()); serverBootstrap.option(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr_parent()); // serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);//??? netty // serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 5000);//??? ?timeout?? serverBootstrap.childOption(ChannelOption.TCP_NODELAY, connectorConfig.isTcp_nodelay()); serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, connectorConfig.isKeepAlive()); serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr()); serverBootstrap.childOption(ChannelOption.SO_LINGER, connectorConfig.getSo_linger()); serverBootstrap.childOption(ChannelOption.SO_SNDBUF, connectorConfig.getSo_sndbuf()); serverBootstrap.childOption(ChannelOption.SO_RCVBUF, connectorConfig.getSo_rcvbuf()); channelFuture = serverBootstrap.bind(connectorConfig.getPort()).sync(); }
From source file:com.wangsan.study.netty.codec.serializable.netty.SubReqClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO/* w w w .j a v a 2 s . c om*/ EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // max? new ObjectDecoder(1024, ClassResolvers.cacheDisabled(this.getClass().getClassLoader()))); ch.pipeline().addLast(new ObjectEncoder()); ch.pipeline().addLast(new SubReqClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.weibo.api.motan.transport.netty.NettyClient.java
License:Apache License
/** * ? netty clientBootstrap/*www .ja v a 2 s .co m*/ */ private void initClientBootstrap() { bootstrap = new Bootstrap(); // ?connectTimeout500msnetty nio?BossThread? // ?timeout? int timeout = getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ?? final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue()); EventLoopGroup group = new NioEventLoopGroup(); bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout) .handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new NettyDecoder(codec, NettyClient.this, maxContentLength)); pipeline.addLast(new NettyEncoder(codec, NettyClient.this)); pipeline.addLast(new NettyChannelHandler(NettyClient.this, new MessageHandler() { @Override public Object handle(Channel channel, Object message) { Response response = (Response) message; NettyResponseFuture responseFuture = NettyClient.this .removeCallback(response.getRequestId()); if (responseFuture == null) { LoggerUtil.warn( "NettyClient has response from server, but resonseFuture not exist, requestId={}", response.getRequestId()); return null; } if (response.getException() != null) { responseFuture.onFailure(response); } else { responseFuture.onSuccess(response); } return null; } })); } }); }
From source file:com.weibo.api.motan.transport.netty.NettyServer.java
License:Apache License
private synchronized void initServerBootstrap() { boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue()); final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue()); int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue()); int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), URLParamType.workerQueueSize.getIntValue()); int minWorkerThread = 0, maxWorkerThread = 0; if (shareChannel) { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER); } else {//from w ww . ja v a 2s . c o m minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER); } standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor : new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true)); standardThreadExecutor.prestartAllCoreThreads(); // ?? channelManage = new NettyServerChannelManage(maxServerConnection); final NettyChannelHandler handler = new NettyChannelHandler(NettyServer.this, messageHandler, standardThreadExecutor); EventLoopGroup bossGroup = new NioEventLoopGroup(1, new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, String.format("NettyBoss_%d", this.threadIndex.incrementAndGet())); } }); EventLoopGroup workerGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(channelManage); ch.pipeline().addLast(new NettyEncoder(codec, NettyServer.this)); ch.pipeline().addLast(new NettyDecoder(codec, NettyServer.this, maxContentLength)); ch.pipeline().addLast(handler); } }); }
From source file:com.weibo.api.motan.transport.netty4.client.Netty4Client.java
License:Apache License
/** * ? netty clientBootstrap/* w ww .j a va 2 s . com*/ */ private void initClientBootstrap() { bootstrap = new Bootstrap(); NioEventLoopGroup group = new NioEventLoopGroup(); bootstrap.group(group).channel(NioSocketChannel.class) .handler(new Netty4ClientInitializer(url, codec, this)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); /* ?connectTimeout500msnetty nio?BossThread? ?timeout? */ int timeout = getUrl().getIntParameter(URLParamType.requestTimeout.getName(), URLParamType.requestTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout); }
From source file:com.witjit.game.client.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) {/*from ww w . j av a2s . com*/ sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); sendData(f.channel()); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }