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:MultiThreadClient.java
License:Apache License
public void run() throws Exception { try {/*from w ww . ja va 2 s . c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelDuplexHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println( index + "-??:" + msg + "Read:" + Thread.currentThread()); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { ChannelFuture future = ctx.writeAndFlush(msg, promise); System.out.println(index + "-Write:" + Thread.currentThread()); Thread.yield(); Thread.yield(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { System.out.println(index + "-Listener" + "Lintener:" + Thread.currentThread()); } }); } }); // Make the connection attempt. ChannelFuture f = b.connect(host, port).sync(); for (int i = 0; i < 10; i++) { f.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[10])); } // Wait until the connection is closed. f.channel().closeFuture(); } finally { //group.shutdownGracefully(); } }
From source file:NettyHttpListner.java
License:Apache License
public void start() { System.out.println("Starting the server..."); System.out.println("Starting Inbound Http Listner on Port " + this.port); // Configure SSL. SslContext sslCtx = null;//from w w w.j a v a2s . c o m if (SSL) { try { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (CertificateException ex) { Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex); } catch (SSLException ex) { Logger.getLogger(NettyHttpListner.class.getName()).log(Level.SEVERE, null, ex); } } commonEventLoopGroup = new NioEventLoopGroup(bossGroupSize); // bossGroup = new NioEventLoopGroup(bossGroupSize); // workerGroup = new NioEventLoopGroup(workerGroupSize); try { ServerBootstrap b = new ServerBootstrap(); // b.commonEventLoopGroup(bossGroup, workerGroup) b.group(commonEventLoopGroup).channel(NioServerSocketChannel.class) .childHandler( new NettyHttpTransportHandlerInitializer(HOST, HOST_PORT, maxConnectionsQueued, sslCtx)) .childOption(ChannelOption.AUTO_READ, false); b.option(ChannelOption.TCP_NODELAY, true); b.childOption(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_BACKLOG, maxConnectionsQueued); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000); b.option(ChannelOption.SO_SNDBUF, 1048576); b.option(ChannelOption.SO_RCVBUF, 1048576); b.childOption(ChannelOption.SO_RCVBUF, 1048576); b.childOption(ChannelOption.SO_SNDBUF, 1048576); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); Channel ch = null; try { ch = b.bind(port).sync().channel(); ch.closeFuture().sync(); System.out.println("Inbound Listner Started"); } catch (InterruptedException e) { System.out.println("Exception caught"); } } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:HttpRouterServer.java
License:Apache License
public static void main(String[] args) throws Exception { Router<String> router = new Router<String>().GET(PUBLIC_DIR + ":id", "public").GET("/", "index") .GET(PUBLIC_DIR, "index") // .GET("/image", "base64") // .GET("/img", "image") // .GET("/", "Index page") // .GET("/articles/:id", "Article show page") .notFound("404 Not Found"); System.out.println(router);//from w ww . j a va2s .c om NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE) .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE) .channel(NioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router)); Channel ch = b.bind(PORT).sync().channel(); System.out.println("Server started: http://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:NettyHttpTransportSourceHandler.java
License:Apache License
/** * activating registered handler to accept events. * * @param ctx//from www . java 2 s .c o m * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()); b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000); b.option(ChannelOption.SO_SNDBUF, 1048576); b.option(ChannelOption.SO_RCVBUF, 1048576); ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT); outboundChannel = f.channel(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // connection complete start to read first data inboundChannel.read(); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); }
From source file:TestTCPServer.java
License:Open Source License
public static void main(String... args) throws Throwable { IOService service = new IOService(); TCPAcceptor acceptor = new TCPAcceptor(service); acceptor.setOption(ChannelOption.SO_BACKLOG, 3); acceptor.setChildOption(ChannelOption.TCP_NODELAY, true); acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true); acceptor.bind(4321);/*w w w . java 2s. c o m*/ TCPSocket con = acceptor.accept(); ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000); byte[] bytea = new byte[buffer.capacity()]; long bytes; System.out.println("Connected " + con.remoteEndpoint()); bytes = con.receive(buffer); while (bytes != -1 && buffer.getByte(0) != 4) { buffer.readBytes(bytea, 0, (int) bytes); System.out.print(new String(bytea, 0, (int) bytes)); buffer.readerIndex(0).writerIndex(0); con.send(buffer, (int) bytes); buffer.readerIndex(0).writerIndex(0); bytes = con.receive(buffer); } System.out.println("Connection closed"); con.close(); acceptor.close(); service.cancel(); }
From source file:alluxio.client.netty.NettyClient.java
License:Apache License
/** * Creates and returns a new Netty client bootstrap for clients to connect to remote servers. * * @param handler the handler that should be added to new channel pipelines * @return the new client {@link Bootstrap} */// w w w .ja va2 s .co m public static Bootstrap createClientBootstrap(final ClientHandler handler) { final Bootstrap boot = new Bootstrap(); boot.group(WORKER_GROUP).channel(CLIENT_CHANNEL_CLASS); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.option(ChannelOption.TCP_NODELAY, true); boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); boot.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(RPCMessage.createFrameDecoder()); pipeline.addLast(ENCODER); pipeline.addLast(DECODER); pipeline.addLast(handler); } }); return boot; }
From source file:alluxio.network.netty.NettyClient.java
License:Apache License
/** * Creates and returns a new Netty client bootstrap for clients to connect to remote servers. * * @param address the socket address// w w w. j a v a2 s.co m * @return the new client {@link Bootstrap} */ public static Bootstrap createClientBootstrap(SocketAddress address) { final Bootstrap boot = new Bootstrap(); boot.group(WORKER_GROUP).channel( NettyUtils.getClientChannelClass(NettyUtils.CHANNEL_TYPE, !(address instanceof InetSocketAddress))); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.option(ChannelOption.TCP_NODELAY, true); boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (NettyUtils.CHANNEL_TYPE == ChannelType.EPOLL) { boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } // After 10 missed heartbeat attempts and no write activity, the server will close the channel. final long timeoutMs = Configuration.getMs(PropertyKey.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS); final long heartbeatPeriodMs = Math.max(timeoutMs / 10, 1); boot.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(RPCMessage.createFrameDecoder()); pipeline.addLast(ENCODER); pipeline.addLast(DECODER); pipeline.addLast(new IdleStateHandler(0, heartbeatPeriodMs, 0, TimeUnit.MILLISECONDS)); pipeline.addLast(new IdleWriteHandler()); } }); return boot; }
From source file:basic.TimeClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO// w w w .ja va 2 s .c o m 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(new TimeClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:be.yildizgames.module.network.netty.server.ServerNetty.java
License:MIT License
/** * Create a new Netty server./* w w w. ja v a2s . c om*/ * */ //@requires bootstrap != null. //@requires port > 0 < 65535. private ServerNetty() { super(); EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); this.bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class); this.bootstrap.option(ChannelOption.TCP_NODELAY, true); this.bootstrap.option(ChannelOption.SO_KEEPALIVE, true); }
From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java
License:Apache License
/** * Tulio Ribeiro Connect to specific replica and returns the ChannelFuture. * sessionClientToReplica is replaced with the new connection. Removed redundant * code./*from www .j a v a 2s.c om*/ */ public synchronized ChannelFuture connectToReplica(int replicaId, SecretKeyFactory fac) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { String str = this.clientId + ":" + replicaId; PBEKeySpec spec = TOMUtil.generateKeySpec(str.toCharArray()); SecretKey authKey = fac.generateSecret(spec); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.TCP_NODELAY, true); b.option(ChannelOption.SO_SNDBUF, tcpSendBufferSize); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMsec); b.handler(getChannelInitializer()); ChannelFuture channelFuture = b.connect(controller.getRemoteAddress(replicaId)); NettyClientServerSession ncss = new NettyClientServerSession(channelFuture.channel(), replicaId); sessionClientToReplica.put(replicaId, ncss); return channelFuture; }