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.allanbank.mongodb.netty.NettyTransport.java
License:Apache License
/** * Creates a new NettySocketConnection.// w w w . j av a 2 s . co m * * @param server * The MongoDB server to connect to. * @param config * The configuration for the Connection to the MongoDB server. * @param encoderCache * Cache used for encoding strings. * @param decoderCache * Cache used for decoding strings. * @param responseListener * The listener for the status of the transport/connection. * @param bootstrap * The seeded bootstrap for creating the {@link Channel}. * * @throws IOException * On a failure connecting to the MongoDB server. */ public NettyTransport(final Server server, final MongoClientConfiguration config, final StringEncoderCache encoderCache, final StringDecoderCache decoderCache, final TransportResponseListener responseListener, final Bootstrap bootstrap) throws IOException { myEncoderCache = encoderCache; // These are critical settings for performance/function. bootstrap.option(ChannelOption.TCP_NODELAY, Boolean.TRUE); bootstrap.option(ChannelOption.AUTO_READ, Boolean.TRUE); bootstrap.handler(new NettyChannelInit(config, decoderCache, responseListener)); Channel channel = null; final Iterator<InetSocketAddress> addrIter = server.getAddresses().iterator(); IOException error = null; while (addrIter.hasNext() && (channel == null)) { final InetSocketAddress address = addrIter.next(); try { channel = bootstrap.connect(address).await().channel(); } catch (final InterruptedException e) { error = new IOException("Failed to wait for the connection to complete.", e); } catch (final RuntimeException e) { error = new IOException("Failed to create a connection to '" + address + "'.", e); } } if (channel != null) { myChannel = channel; } else if (error != null) { throw error; } else { throw new IOException("Failed to create a connection to the server: " + server.getAddresses()); } }
From source file:com.ancun.netty.httpserver.HttpServer.java
License:Apache License
private void setBootstrapOptions(ServerBootstrap bootstrap) { bootstrap.option(ChannelOption.SO_KEEPALIVE, useKeepAlive()); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); bootstrap.option(ChannelOption.TCP_NODELAY, useTcpNoDelay()); bootstrap.option(ChannelOption.SO_KEEPALIVE, serverSettings.isKeepAlive()); bootstrap.option(ChannelOption.SO_REUSEADDR, shouldReuseAddress()); bootstrap.option(ChannelOption.SO_LINGER, getSoLinger()); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeoutMillis()); bootstrap.option(ChannelOption.SO_RCVBUF, getReceiveBufferSize()); bootstrap.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE); bootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)); bootstrap.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE); bootstrap.childOption(ChannelOption.SO_RCVBUF, getReceiveBufferSize()); bootstrap.childOption(ChannelOption.SO_REUSEADDR, shouldReuseAddress()); }
From source file:com.antsdb.saltedfish.server.mysql.MysqlClient.java
License:Open Source License
private void run(EventLoopGroup pool, MysqlClientHandler handler) throws InterruptedException { Bootstrap b = new Bootstrap(); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override// w w w .j ava 2 s. c o m protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ReplicationPacketDecoder(handler), handler); } }; b.group(pool).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(initializer); this.future = b.connect(this.host, this.port).sync(); }
From source file:com.baidu.jprotobuf.pbrpc.transport.RpcClient.java
License:Apache License
public RpcClient(Class<? extends Channel> clientChannelClass, RpcClientOptions rpcClientOptions) { this.workerGroup = new NioEventLoopGroup(); this.group(workerGroup); this.channel(clientChannelClass); this.handler(new RpcClientPipelineinitializer(this)); this.rpcClientOptions = rpcClientOptions; this.option(ChannelOption.SO_REUSEADDR, rpcClientOptions.isReuseAddress()); this.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOptions.getConnectTimeout()); this.option(ChannelOption.SO_SNDBUF, rpcClientOptions.getSendBufferSize()); this.option(ChannelOption.SO_RCVBUF, rpcClientOptions.getSendBufferSize()); this.option(ChannelOption.SO_KEEPALIVE, rpcClientOptions.isKeepAlive()); this.option(ChannelOption.TCP_NODELAY, rpcClientOptions.getTcpNoDelay()); this.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, new DefaultMessageSizeEstimator(rpcClientOptions.getReceiveBufferSize())); // add count/*from w w w .ja v a 2s . co m*/ INSTANCE_COUNT.incrementAndGet(); }
From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java
License:Apache License
public RpcServer(Class<? extends ServerChannel> serverChannelClass, RpcServerOptions serverOptions, RpcServiceRegistry rpcServiceRegistry) { if (rpcServiceRegistry == null) { throw new RuntimeException("protperty 'rpcServiceRegistry ' is null."); }/*from w ww. j a va 2 s.co m*/ if (serverOptions == null) { serverOptions = new RpcServerOptions(); } this.bossGroup = new NioEventLoopGroup(serverOptions.getAcceptorThreads()); this.workerGroup = new NioEventLoopGroup(serverOptions.getWorkThreads()); this.group(this.bossGroup, this.workerGroup); this.channel(serverChannelClass); this.option(ChannelOption.SO_BACKLOG, serverOptions.getBacklog()); this.childOption(ChannelOption.SO_KEEPALIVE, serverOptions.isKeepAlive()); this.childOption(ChannelOption.SO_REUSEADDR, true); this.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); this.childOption(ChannelOption.TCP_NODELAY, serverOptions.isTcpNoDelay()); this.childOption(ChannelOption.SO_LINGER, serverOptions.getSoLinger()); this.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, serverOptions.getConnectTimeout()); this.childOption(ChannelOption.SO_RCVBUF, serverOptions.getReceiveBufferSize()); this.childOption(ChannelOption.SO_SNDBUF, serverOptions.getSendBufferSize()); this.rpcServiceRegistry = rpcServiceRegistry; // do register meta service rpcServiceRegistry.doRegisterMetaService(); this.rpcServerOptions = serverOptions; this.rpcServerPipelineInitializer = new RpcServerPipelineInitializer(rpcServiceRegistry, rpcServerOptions); this.childHandler(rpcServerPipelineInitializer); }
From source file:com.baidu.rigel.biplatform.ma.file.client.monitor.FileServerMonitor.java
License:Open Source License
/** * ?//from w ww . j a v a2 s . c o m */ public void start() throws Exception { EventLoopGroup work = new NioEventLoopGroup(); Bootstrap strap = new Bootstrap(); try { strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel chl) throws Exception { // ?? chl.pipeline().addLast(new ObjectDecoder(1024, ClassResolvers.cacheDisabled(FileServerMonitor.class.getClassLoader()))); chl.pipeline().addLast(new ObjectEncoder()); chl.pipeline().addLast(new FileServerMonitor()); } }); ChannelFuture future = strap.connect(new InetSocketAddress(host, port)); future.channel().closeFuture().sync(); } finally { executor.execute(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(3); ChannelFuture future = strap.connect("localhost", 9090).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } }); } }
From source file:com.baidu.rigel.biplatform.ma.file.client.service.impl.FileServerClient.java
License:Open Source License
/** * ?//from w w w. jav a2s . c o m * * @param server * ?? * @param port * ?? * @param request * * @return */ public Response doRequest(String server, int port, final Request request) { EventLoopGroup work = new NioEventLoopGroup(1); String message = null; try { final Response rs = new Response(ResponseStatus.FAIL, "failed", null); ChannelHandlerAdapter requestHandler = new ChannelHandlerAdapter() { /** * {@inheritDoc} */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("successfully connect to file server"); ctx.write(request); ctx.flush(); } /** * {@inheritDoc} */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("successfuly recieve message from file server {}", msg); Response tmpRs = (Response) msg; rs.setDatas(tmpRs.getDatas()); rs.setMessage(tmpRs.getMessage()); rs.setStatus(tmpRs.getStatus()); ctx.close(); } /** * {@inheritDoc} */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } /** * {@inheritDoc} */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause.getMessage()); rs.setMessage(cause.getMessage()); rs.setStatus(ResponseStatus.FAIL); ctx.close(); } }; Bootstrap strap = new Bootstrap(); strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel chl) throws Exception { // ?? chl.pipeline().addLast(new ObjectDecoder( ClassResolvers.cacheDisabled(requestHandler.getClass().getClassLoader()))); chl.pipeline().addLast(new ObjectEncoder()); chl.pipeline().addLast(requestHandler); } }); long begin = System.currentTimeMillis(); logger.debug("Begin invoke do file operation request ... ..."); ChannelFuture future = strap.connect(server, port); future.channel().closeFuture().sync(); logger.debug( "Success execute request option cost time: " + (System.currentTimeMillis() - begin) + "ms"); return rs; } catch (InterruptedException e) { logger.error(e.getMessage(), e); message = e.getMessage(); } finally { work.shutdownGracefully(); } Response rs = new Response(ResponseStatus.FAIL, message, null); return rs; }
From source file:com.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchClient.java
License:Open Source License
public IndexAndSearchClient() { // channelMaps = new ConcurrentHashMap<NodeAddress, Channel>(); actionHandlerMaps = new ConcurrentHashMap<String, ChannelHandler>(); b = new Bootstrap(); group = new NioEventLoopGroup(); b.group(group);/*www. ja v a 2 s .c o m*/ b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("encode", new ObjectEncoder()); pipeline.addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null))); // pipeline.addLast("frameencoder",new LengthFieldPrepender(4,false)); // pipeline.addLast("framedecoder",new LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4)); } }); logger.info("IndexAndSearchClient init finished"); }
From source file:com.beeswax.http.server.HttpServer.java
License:Apache License
public void run() throws InterruptedException { // Create event loop groups. One for incoming connections handling and // second for handling actual event by workers final NioEventLoopGroup bossGroup = new NioEventLoopGroup(serverConfig.bossGroupSize); final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w w w .j a va 2 s . c om ServerBootstrap bootStrap = new ServerBootstrap(); bootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) // SO_BACKLOG : The maximum queue length for incoming connections. .option(ChannelOption.SO_BACKLOG, serverConfig.backlogSize) // TCP_NODELAY: option to disable Nagle's algorithm to achieve lower latency on every packet sent .option(ChannelOption.TCP_NODELAY, serverConfig.tcpNodelay) // SO_KEEPALIVE: option to enable keep-alive packets for a socket connection .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.keepAlive) .childHandler(new HttpServerChannelInitializer(serverConfig, handlerFactory)); // bind to port final ChannelFuture channelFuture = bootStrap.bind(serverConfig.port).sync(); // Wait until the server socket is closed. channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.book.netty5.client.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO// ww w .j av a 2 s . c om 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(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); // ?? ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { // ???????? executor.execute(new Runnable() { public void run() { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ??? } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } }