Search in sources :

Example 51 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project ambry by linkedin.

the class NettyServerFactoryTest method doGetNettyServerTest.

/**
 * Test that a {@link NettyServer} can be constructed by the factory.
 * @param properties the {@link Properties} to use.
 * @param sslFactory the {@link SSLFactory} to use.
 */
private void doGetNettyServerTest(Properties properties, SSLFactory sslFactory) {
    VerifiableProperties verifiableProperties = new VerifiableProperties(properties);
    NettyConfig nettyConfig = new NettyConfig(verifiableProperties);
    NettyServerFactory nettyServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), REST_REQUEST_HANDLER, PUBLIC_ACCESS_LOGGER, REST_SERVER_STATE, sslFactory);
    NioServer nioServer = nettyServerFactory.getNioServer();
    assertNotNull("No NioServer returned", nioServer);
    assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName());
    Map<Integer, ChannelInitializer<SocketChannel>> channelInitializers = nettyServerFactory.channelInitializers;
    if (nettyConfig.nettyServerEnableSSL && sslFactory != null) {
        assertEquals("Expected two ChannelInitializers when SSLFactory is not null", 2, channelInitializers.size());
        assertNotNull("No ChannelInitializer for SSL port", channelInitializers.get(nettyConfig.nettyServerSSLPort));
    } else {
        assertEquals("Expected one ChannelInitializer when SSLFactory is null", 1, channelInitializers.size());
    }
    assertNotNull("No ChannelInitializer for plaintext port", channelInitializers.get(nettyConfig.nettyServerPort));
}
Also used : VerifiableProperties(com.github.ambry.config.VerifiableProperties) MetricRegistry(com.codahale.metrics.MetricRegistry) ChannelInitializer(io.netty.channel.ChannelInitializer) NettyConfig(com.github.ambry.config.NettyConfig)

Example 52 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project camel by apache.

the class LumberjackUtil method sendMessages.

static List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters) throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();
        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }
                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        assertEquals(msg.readUnsignedByte(), (short) '2');
                        assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };
        // Connect to the server
        Channel channel = //
        new Bootstrap().group(//
        eventLoopGroup).channel(//
        NioSocketChannel.class).handler(//
        initializer).connect("127.0.0.1", port).sync().channel();
        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window15"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.close();
        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 53 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project xian by happyyangyuan.

the class OAuthServer method startServer.

public void startServer() {
    synchronized (LOCK) {
        if (started.get()) {
            LOG.warn("已启动,不允许重复启动");
            return;
        }
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {

                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder()).addLast("decoder", new HttpRequestDecoder()).addLast("aggregator", new HttpObjectAggregator(4096)).addLast("handler", new OAuth20Handler());
                }
            }).option(ChannelOption.SO_BACKLOG, 10240).option(ChannelOption.SO_REUSEADDR, true);
            LOG.info(String.format("[OAuth] oauth server is about to start on port {%s} ", PORT));
            parentChannel = b.bind(PORT).sync().channel();
            LOG.info(String.format("[OAuth] oauth server started on port {%s} ", PORT));
            ThreadPoolManager.execute(() -> {
                try {
                    LOG.debug("[OAuth] Wait until the server socket is closed.");
                    parentChannel.closeFuture().sync();
                } catch (Throwable ee) {
                    LOG.error(ee);
                } finally {
                    LOG.info("[OAuth] 准备shutdown oauth server");
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                    LOG.info("[OAuth] oauth server shutdown完毕!");
                }
            });
            started.set(true);
        } catch (Throwable e) {
            LOG.error("[OAuth] oauth server 启动失败", e);
            started.set(false);
        }
    }
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 54 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project bgpcep by opendaylight.

the class BGPReconnectPromise method connectSessionPromise.

private BGPProtocolSessionPromise<S> connectSessionPromise(final InetSocketAddress address, final int retryTimer, final Bootstrap bootstrap, final BGPPeerRegistry peerRegistry, final ChannelPipelineInitializer<S> initializer) {
    final BGPProtocolSessionPromise<S> sessionPromise = new BGPProtocolSessionPromise<>(address, retryTimer, bootstrap, peerRegistry);
    final ChannelHandler chInit = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) {
            initializer.initializeChannel(channel, sessionPromise);
        }
    };
    bootstrap.handler(chInit);
    sessionPromise.connect();
    LOG.debug("Client created.");
    return sessionPromise;
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandler(io.netty.channel.ChannelHandler) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 55 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project activemq-artemis by apache.

the class WebServerComponentTest method simpleServer.

@Test
public void simpleServer() throws Exception {
    WebServerDTO webServerDTO = new WebServerDTO();
    webServerDTO.bind = "http://localhost:0";
    webServerDTO.path = "webapps";
    WebServerComponent webServerComponent = new WebServerComponent();
    Assert.assertFalse(webServerComponent.isStarted());
    webServerComponent.configure(webServerDTO, "./src/test/resources/", "./src/test/resources/");
    testedComponents.add(webServerComponent);
    webServerComponent.start();
    final int port = webServerComponent.getPort();
    // Make the connection attempt.
    CountDownLatch latch = new CountDownLatch(1);
    final ClientHandler clientHandler = new ClientHandler(latch);
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(clientHandler);
        }
    });
    Channel ch = bootstrap.connect("localhost", port).sync().channel();
    URI uri = new URI(URL);
    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaderNames.HOST, "localhost");
    // Send the HTTP request.
    ch.writeAndFlush(request);
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(clientHandler.body, "12345");
    // Wait for the server to close the connection.
    ch.close();
    Assert.assertTrue(webServerComponent.isStarted());
    webServerComponent.stop(true);
    Assert.assertFalse(webServerComponent.isStarted());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) WebServerDTO(org.apache.activemq.artemis.dto.WebServerDTO) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) WebServerComponent(org.apache.activemq.artemis.component.WebServerComponent) ChannelInitializer(io.netty.channel.ChannelInitializer) Test(org.junit.Test)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)86 Channel (io.netty.channel.Channel)59 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)30 ChannelPipeline (io.netty.channel.ChannelPipeline)26 EventLoopGroup (io.netty.channel.EventLoopGroup)26 LocalServerChannel (io.netty.channel.local.LocalServerChannel)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 SocketChannel (io.netty.channel.socket.SocketChannel)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 Map (java.util.Map)12 CountDownLatch (java.util.concurrent.CountDownLatch)12