Java Code Examples for io.netty.bootstrap.ServerBootstrap#childHandler()

The following examples show how to use io.netty.bootstrap.ServerBootstrap#childHandler() . 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: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example 2
Source File: ProtocolViolationTests.java    From netty-zmtp with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  final ServerBootstrap serverBootstrap = new ServerBootstrap();
  serverBootstrap.channel(NioServerSocketChannel.class);
  bossGroup = new NioEventLoopGroup(1);
  group = new NioEventLoopGroup();
  serverBootstrap.group(bossGroup, group);
  serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
    @Override
    protected void initChannel(final NioSocketChannel ch) throws Exception {
      ch.pipeline().addLast(
          ZMTPCodec.builder()
              .protocol(ZMTP20)
              .socketType(ROUTER)
              .localIdentity(identity)
              .build(),
          mockHandler);
    }
  });

  serverChannel = serverBootstrap.bind(new InetSocketAddress("localhost", 0))
      .awaitUninterruptibly().channel();
  serverAddress = (InetSocketAddress) serverChannel.localAddress();
}
 
Example 3
Source File: DefaultRegistryServer.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture bind(SocketAddress localAddress) {
    ServerBootstrap boot = bootstrap();

    initChannelFactory();

    boot.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(
                    new IdleStateChecker(timer, JConstants.READER_IDLE_TIME_SECONDS, 0, 0),
                    idleStateTrigger,
                    new MessageDecoder(),
                    encoder,
                    ackEncoder,
                    handler);
        }
    });

    setOptions();

    return boot.bind(localAddress);
}
 
Example 4
Source File: HttpTestServer.java    From crate with Apache License 2.0 6 votes vote down vote up
public void run() throws InterruptedException {
    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    group = new NioEventLoopGroup();
    bootstrap.group(group);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new HttpRequestDecoder());
            pipeline.addLast("encoder", new HttpResponseEncoder());
            pipeline.addLast("deflater", new HttpContentCompressor());
            pipeline.addLast("handler", new HttpTestServerHandler());
        }
    });

    // Bind and start to accept incoming connections.
    channel = bootstrap.bind(new InetSocketAddress(port)).sync().channel();
}
 
Example 5
Source File: NettyServerBootstrap.java    From netty with Apache License 2.0 6 votes vote down vote up
private void bind() throws InterruptedException {
    EventLoopGroup boss=new NioEventLoopGroup();
    EventLoopGroup worker=new NioEventLoopGroup();
    ServerBootstrap bootstrap=new ServerBootstrap();
    bootstrap.group(boss,worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline p = socketChannel.pipeline();
            p.addLast(new ObjectEncoder());
            p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            p.addLast(new NettyServerHandler());
        }
    });
    ChannelFuture f= bootstrap.bind(port).sync();
    if(f.isSuccess()){
        System.out.println("server start---------------");
    }
}
 
Example 6
Source File: OioEventLoopTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testTooManyAcceptedChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    assertThat(s.getInputStream().read(), is(-1));
    s.close();

    g.shutdownGracefully();
}
 
Example 7
Source File: TcpServer.java    From krpc with MIT License 6 votes vote down vote up
protected static void run() throws Exception {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);
		b.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new ByteArrayDecoder());
				pipeline.addLast("encoder", new ByteArrayEncoder());
//				pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//				pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
				pipeline.addLast(new TcpServerHandler());
			}
		});

		// b.bind(IP, PORT).sync();
		ChannelFuture f = b.bind(PORT).sync(); // (7)

		f.channel().closeFuture().sync();

		System.out.println("TCP服务器已启动");
	}
 
Example 8
Source File: HttpUploadServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " +
                (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 9
Source File: OioEventLoopTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTooManyClientChannels() throws Exception {
    EventLoopGroup g = new OioEventLoopGroup(1);
    ServerBootstrap sb = new ServerBootstrap();
    sb.channel(OioServerSocketChannel.class);
    sb.group(g);
    sb.childHandler(new ChannelInboundHandlerAdapter());
    ChannelFuture f1 = sb.bind(0);
    f1.sync();

    Bootstrap cb = new Bootstrap();
    cb.channel(OioSocketChannel.class);
    cb.group(g);
    cb.handler(new ChannelInboundHandlerAdapter());
    ChannelFuture f2 = cb.connect(NetUtil.LOCALHOST, ((InetSocketAddress) f1.channel().localAddress()).getPort());
    f2.await();

    assertThat(f2.cause(), is(instanceOf(ChannelException.class)));
    assertThat(f2.cause().getMessage().toLowerCase(), containsString("too many channels"));

    final CountDownLatch notified = new CountDownLatch(1);
    f2.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            notified.countDown();
        }
    });

    notified.await();
    g.shutdownGracefully();
}
 
Example 10
Source File: CIMNioSocketAcceptor.java    From cim with Apache License 2.0 5 votes vote down vote up
private void bindAppPort(){
	appBossGroup = new NioEventLoopGroup();
	appWorkerGroup = new NioEventLoopGroup();
	ServerBootstrap bootstrap = createServerBootstrap(appBossGroup,appWorkerGroup);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch){
			ch.pipeline().addLast(new AppMessageDecoder());
			ch.pipeline().addLast(new AppMessageEncoder());
			ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
			ch.pipeline().addLast(new IdleStateHandler(READ_IDLE_TIME, WRITE_IDLE_TIME, 0));
			ch.pipeline().addLast(channelEventHandler);
		}
	});

	ChannelFuture channelFuture = bootstrap.bind(appPort).syncUninterruptibly();
	channelFuture.channel().newSucceededFuture().addListener(future -> {
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   App Socket Server started on port {}.                        *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, appPort);
	});
	channelFuture.channel().closeFuture().addListener(future -> this.destroy(appBossGroup,appWorkerGroup));
}
 
Example 11
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Reproduces the issue #1679
 */
@Test
public void testFlushAfterGatheredFlush() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                // Trigger a gathering write by writing two buffers.
                ctx.write(Unpooled.wrappedBuffer(new byte[] { 'a' }));
                ChannelFuture f = ctx.write(Unpooled.wrappedBuffer(new byte[] { 'b' }));
                f.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // This message must be flushed
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(new byte[]{'c'}));
                    }
                });
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        DataInput in = new DataInputStream(s.getInputStream());
        byte[] buf = new byte[3];
        in.readFully(buf);

        assertThat(new String(buf, CharsetUtil.US_ASCII), is("abc"));

        s.close();
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 12
Source File: ThreadServerSocket.java    From IMServer with Apache License 2.0 5 votes vote down vote up
public void startSocket() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(boss,worker);

        boot.channel(NioServerSocketChannel.class);
        boot.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,0,4,-4,0,false));
                ch.pipeline().addLast(new ByteToPacketCodec());
                ch.pipeline().addLast(new LoginChannelHandler(listener));
                ch.pipeline().addLast(new PacketChannelHandler());
            }
        });

        boot.option(ChannelOption.SO_BACKLOG,128);
        boot.childOption(ChannelOption.SO_KEEPALIVE,true);
        channelFuture = boot.bind(port).sync();
        System.out.println("服务器"+port+"开启成功...");
        channelFuture.channel().closeFuture().sync();
    }finally {
        boss.shutdownGracefully().sync();
        worker.shutdownGracefully().sync();
        channelFuture = null;
        System.out.println("服务器关闭成功...");
    }
}
 
Example 13
Source File: Server.java    From LittleProxy-mitm with Apache License 2.0 5 votes vote down vote up
protected Server start(SslContext sslCtx) throws InterruptedException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);
    b.childHandler(new HttpStaticFileServerInitializer(sslCtx));
    b.bind(getPort());
    return this;
}
 
Example 14
Source File: NettyServer.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 设置网络IO处理,默认实现HTTP
 */
private void applyChildHandler(ServerBootstrap bootstrap, ProtocolType protocol) {
    if (protocol.equals(ProtocolType.HTTP)) {
        bootstrap.childHandler(httpChannelInitializer);
    } else if (protocol.equals(ProtocolType.SOCKET)) {
        {
            log.info("...not implement...");
        }
    } else if (protocol.equals(ProtocolType.WEB_SOCKET)) {
        bootstrap.childHandler(webSocketChannelInitializer);
    }
}
 
Example 15
Source File: SocketSpdyEchoTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private static void testSpdyEcho(
        ServerBootstrap sb, Bootstrap cb, final SpdyVersion version, boolean autoRead) throws Throwable {

    ByteBuf frames;
    switch (version) {
    case SPDY_3_1:
        frames = createFrames(3);
        break;
    default:
        throw new IllegalArgumentException("unknown version");
    }

    final SpdyEchoTestServerHandler sh = new SpdyEchoTestServerHandler(autoRead);
    final SpdyEchoTestClientHandler ch = new SpdyEchoTestClientHandler(frames.copy(), autoRead);

    sb.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            channel.pipeline().addLast(
                    new SpdyFrameCodec(version),
                    sh);
        }
    });

    cb.handler(ch);

    Channel sc = sb.localAddress(0).bind().sync().channel();
    int port = ((InetSocketAddress) sc.localAddress()).getPort();

    Channel cc = cb.remoteAddress(NetUtil.LOCALHOST, port).connect().sync().channel();
    cc.writeAndFlush(frames);

    while (ch.counter < frames.writerIndex() - ignoredBytes) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}
 
Example 16
Source File: TcpServerChannelManager.java    From openAGV with Apache License 2.0 4 votes vote down vote up
@Override
    public void initialize() {
        if (initialized) {
            LOG.warn("已经初始化,请勿重复初始化");
            return;
        }

        serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        serverBootstrap.group(workerGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
//        TcpServerHandler tcpServerHandler = new TcpServerHandler(clientEntries);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                if (loggingInitially) {
                    ch.pipeline().addFirst(LOGGING_HANDLER_NAME,
                            new LoggingHandler(TcpServerChannelManager.this.getClass()));
                }
                if (readTimeout > 0) {
                    ch.pipeline().addLast(new IdleStateHandler(readTimeout, 0, 0, TimeUnit.MILLISECONDS));
                }
                for (ChannelHandler handler : channelSupplier.get()) {
                    ch.pipeline().addLast(handler);
                }
                ch.pipeline().addLast(new TcpServerHandler(clientEntries));
                ch.pipeline().addLast(new ServerConnectionStateNotifier(clientEntries));
            }

        });
        try {
            serverChannelFuture = serverBootstrap.bind(host, port).sync();
            serverChannelFuture.addListener((ChannelFuture future) -> {
                if (future.isSuccess()) {
                    initialized = true;
                    LOG.warn("TcpServerChannelManager绑定[" + host + ":" + port + "]成功");
                } else {
                    throw new RuntimeException("udp绑定[" + host + ":" + port + "]不成功");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            workerGroup.shutdownGracefully();
            throw new RuntimeException("TcpServerChannelManager initialized is " + isInitialized() + ", exception message:  " + e.getMessage());
        }
    }
 
Example 17
Source File: NettyHttpServer.java    From netty-http-server with Apache License 2.0 4 votes vote down vote up
@Override
public void onApplicationEvent(@NonNull ApplicationStartedEvent event) {

    ServerBootstrap bootstrap = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childOption(NioChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(NioChannelOption.SO_REUSEADDR,true);
    bootstrap.childOption(NioChannelOption.SO_KEEPALIVE,false);
    bootstrap.childOption(NioChannelOption.SO_RCVBUF, 2048);
    bootstrap.childOption(NioChannelOption.SO_SNDBUF, 2048);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) {
            ch.pipeline().addLast("codec", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(512 * 1024));
            ch.pipeline().addLast("logging", new FilterLogginglHandler());
            ch.pipeline().addLast("interceptor", interceptorHandler);
            ch.pipeline().addLast("bizHandler", httpServerHandler);
        }
    })
    ;
    ChannelFuture channelFuture = bootstrap.bind(port).syncUninterruptibly().addListener(future -> {
        String logBanner = "\n\n" +
                "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
                "*                                                                                   *\n" +
                "*                                                                                   *\n" +
                "*                   Netty Http Server started on port {}.                         *\n" +
                "*                                                                                   *\n" +
                "*                                                                                   *\n" +
                "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
        LOGGER.info(logBanner, port);
    });
    channelFuture.channel().closeFuture().addListener(future -> {
        LOGGER.info("Netty Http Server Start Shutdown ............");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    });
}
 
Example 18
Source File: SocketCancelWriteTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
public void testCancelWrite(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    final TestHandler sh = new TestHandler();
    final TestHandler ch = new TestHandler();
    final ByteBuf a = Unpooled.buffer().writeByte('a');
    final ByteBuf b = Unpooled.buffer().writeByte('b');
    final ByteBuf c = Unpooled.buffer().writeByte('c');
    final ByteBuf d = Unpooled.buffer().writeByte('d');
    final ByteBuf e = Unpooled.buffer().writeByte('e');

    cb.handler(ch);
    sb.childHandler(sh);

    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect().sync().channel();

    ChannelFuture f = cc.write(a);
    assertTrue(f.cancel(false));
    cc.writeAndFlush(b);
    cc.write(c);
    ChannelFuture f2 = cc.write(d);
    assertTrue(f2.cancel(false));
    cc.writeAndFlush(e);

    while (sh.counter < 3) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException ignore) {
            // Ignore.
        }
    }
    sh.channel.close().sync();
    ch.channel.close().sync();
    sc.close().sync();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
    assertEquals(0, ch.counter);
    assertEquals(Unpooled.wrappedBuffer(new byte[]{'b', 'c', 'e'}), sh.received);
}
 
Example 19
Source File: HttpServer.java    From openzaly with Apache License 2.0 4 votes vote down vote up
public HttpServer() {
	try {
		executor = new SimpleExecutor<Command, CommandResponse>();
		loadExecutor(executor);
		int needThreadNum = Runtime.getRuntime().availableProcessors() + 1;
		int parentNum = 5;// accept from channel socket
		int childNum = needThreadNum * 2 + 5;// give to business handler
		bootstrap = new ServerBootstrap();
		parentGroup = new NioEventLoopGroup(parentNum);
		childGroup = new NioEventLoopGroup(childNum);
		bootstrap.group(parentGroup, childGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		// 接受连接的可连接队列大小
		bootstrap.option(ChannelOption.SO_BACKLOG, 120);
		bootstrap.option(ChannelOption.SO_REUSEADDR, true);
		// 设置缓存大小
		bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
		bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节

		bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 接受缓存区,动态内存分配端的算法
		 */
		bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new HttpResponseEncoder());
				ch.pipeline().addLast(new HttpRequestDecoder());
				ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
				ch.pipeline().addLast("streamer", new ChunkedWriteHandler());
				ch.pipeline().addLast(new HttpServerHandler(executor));
			}
		});
	} catch (Exception e) {
		closeGracefylly();
		logger.error(AkxProject.PLN + " init http server error.", e);
		System.exit(-200);
	}
}
 
Example 20
Source File: NioSocketChannelTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Reproduces the issue #1600
 */
@Test
public void testFlushCloseReentrance() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(1);
    try {
        final Queue<ChannelFuture> futures = new LinkedBlockingQueue<ChannelFuture>();

        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(NioServerSocketChannel.class);
        sb.childOption(ChannelOption.SO_SNDBUF, 1024);
        sb.childHandler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Write a large enough data so that it is split into two loops.
                futures.add(ctx.write(
                        ctx.alloc().buffer().writeZero(1048576)).addListener(ChannelFutureListener.CLOSE));
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
                futures.add(ctx.write(ctx.alloc().buffer().writeZero(1048576)));
                ctx.flush();
            }
        });

        SocketAddress address = sb.bind(0).sync().channel().localAddress();

        Socket s = new Socket(NetUtil.LOCALHOST, ((InetSocketAddress) address).getPort());

        InputStream in = s.getInputStream();
        byte[] buf = new byte[8192];
        for (;;) {
            if (in.read(buf) == -1) {
                break;
            }

            // Wait a little bit so that the write attempts are split into multiple flush attempts.
            Thread.sleep(10);
        }
        s.close();

        assertThat(futures.size(), is(3));
        ChannelFuture f1 = futures.poll();
        ChannelFuture f2 = futures.poll();
        ChannelFuture f3 = futures.poll();
        assertThat(f1.isSuccess(), is(true));
        assertThat(f2.isDone(), is(true));
        assertThat(f2.isSuccess(), is(false));
        assertThat(f2.cause(), is(instanceOf(ClosedChannelException.class)));
        assertThat(f3.isDone(), is(true));
        assertThat(f3.isSuccess(), is(false));
        assertThat(f3.cause(), is(instanceOf(ClosedChannelException.class)));
    } finally {
        group.shutdownGracefully().sync();
    }
}