Search in sources :

Example 71 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project x-pipe by ctripcorp.

the class DefaultRedisKeeperServer method startServer.

protected void startServer() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new LoggingHandler(LogLevel.DEBUG));
            p.addLast(new NettySimpleMessageHandler());
            p.addLast(new NettyMasterHandler(DefaultRedisKeeperServer.this, new CommandHandlerManager(), keeperConfig.getTrafficReportIntervalMillis()));
        }
    });
    serverSocketChannel = (ServerSocketChannel) b.bind(currentKeeperMeta.getPort()).sync().channel();
}
Also used : NettyMasterHandler(com.ctrip.xpipe.redis.keeper.netty.NettyMasterHandler) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NettySimpleMessageHandler(com.ctrip.xpipe.netty.NettySimpleMessageHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) XpipeRuntimeException(com.ctrip.xpipe.exception.XpipeRuntimeException) RedisSlavePromotionException(com.ctrip.xpipe.redis.keeper.exception.RedisSlavePromotionException) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) CommandHandlerManager(com.ctrip.xpipe.redis.keeper.handler.CommandHandlerManager)

Example 72 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project rocketmq-externals by apache.

the class MQTTBridge method init.

private void init() {
    bossGroup = new NioEventLoopGroup(MQTTBridgeConfiguration.threadNumOfBossGroup());
    workerGroup = new NioEventLoopGroup(MQTTBridgeConfiguration.threadNumOfWorkerGroup());
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).localAddress(MQTTBridgeConfiguration.port()).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, MQTTBridgeConfiguration.socketBacklog()).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("mqtt-decoder", new MqttDecoder());
            pipeline.addLast("mqtt-encoder", MqttEncoder.INSTANCE);
            pipeline.addLast("channel-idle-handler", new MqttIdleHandler());
            pipeline.addLast("message-dispatcher", messageDispatcher);
            pipeline.addLast("connection-manager", connectionHandler);
        }
    });
    subscriptionStore = new InMemorySubscriptionStore();
    clientManager = new ClientManagerImpl();
    messageDispatcher = new MessageDispatcher(clientManager);
    connectionHandler = new MqttConnectionHandler(clientManager, subscriptionStore);
    registerMessageHandlers();
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) MqttDecoder(io.netty.handler.codec.mqtt.MqttDecoder) ClientManagerImpl(org.apache.rocketmq.iot.connection.client.impl.ClientManagerImpl) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) MqttIdleHandler(org.apache.rocketmq.iot.protocol.mqtt.handler.MqttIdleHandler) MessageDispatcher(org.apache.rocketmq.iot.protocol.mqtt.handler.MessageDispatcher) MqttConnectionHandler(org.apache.rocketmq.iot.protocol.mqtt.handler.MqttConnectionHandler) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InMemorySubscriptionStore(org.apache.rocketmq.iot.storage.subscription.impl.InMemorySubscriptionStore)

Example 73 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project baseio by generallycloud.

the class EchoServer method main.

public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = NettyUtil.newEventLoopGroup(1);
    EventLoopGroup workerGroup = NettyUtil.newEventLoopGroup(1);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NettyUtil.newServerSocketChannel());
        b.option(ChannelOption.SO_BACKLOG, 50);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new TcpServerHandler());
            }
        });
        // Start the server.
        ChannelFuture f = b.bind(8080).sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 74 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project baseio by generallycloud.

the class MyNettyServer method service.

public static void service() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NettyUtil.newServerSocketChannel());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new IdleStateHandler(5, 10, 20));
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast(new LengthFieldPrepender(4));
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new TcpServerHandler());
        }
    });
    ChannelFuture f = bootstrap.bind(IP, PORT).sync();
    f.channel().closeFuture().sync();
    System.out.println("TCP服务器已启动");
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) StringEncoder(io.netty.handler.codec.string.StringEncoder) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder)

Example 75 with ServerBootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.ServerBootstrap in project riposte by Nike-Inc.

the class Server method startup.

public void startup() throws CertificateException, IOException, InterruptedException {
    if (startedUp) {
        throw new IllegalArgumentException("This Server instance has already started. " + "You can only call startup() once");
    }
    // Figure out what port to bind to.
    int port = Integer.parseInt(System.getProperty("endpointsPort", serverConfig.isEndpointsUseSsl() ? String.valueOf(serverConfig.endpointsSslPort()) : String.valueOf(serverConfig.endpointsPort())));
    // Configure SSL if desired.
    final SslContext sslCtx;
    if (serverConfig.isEndpointsUseSsl()) {
        sslCtx = serverConfig.createSslContext();
    } else {
        sslCtx = null;
    }
    // Configure the server
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    Class<? extends ServerChannel> channelClass;
    // NIO event loop group.
    if (Epoll.isAvailable()) {
        logger.info("The epoll native transport is available. Using epoll instead of NIO. " + "riposte_server_using_native_epoll_transport=true");
        bossGroup = (serverConfig.bossThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numBossThreads()) : new EpollEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
        workerGroup = (serverConfig.workerThreadFactory() == null) ? new EpollEventLoopGroup(serverConfig.numWorkerThreads()) : new EpollEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
        channelClass = EpollServerSocketChannel.class;
    } else {
        logger.info("The epoll native transport is NOT available or you are not running on a compatible " + "OS/architecture. Using NIO. riposte_server_using_native_epoll_transport=false");
        bossGroup = (serverConfig.bossThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numBossThreads()) : new NioEventLoopGroup(serverConfig.numBossThreads(), serverConfig.bossThreadFactory());
        workerGroup = (serverConfig.workerThreadFactory() == null) ? new NioEventLoopGroup(serverConfig.numWorkerThreads()) : new NioEventLoopGroup(serverConfig.numWorkerThreads(), serverConfig.workerThreadFactory());
        channelClass = NioServerSocketChannel.class;
    }
    eventLoopGroups.add(bossGroup);
    eventLoopGroups.add(workerGroup);
    // Figure out which channel initializer should set up the channel pipelines for new channels.
    ChannelInitializer<SocketChannel> channelInitializer = serverConfig.customChannelInitializer();
    if (channelInitializer == null) {
        DistributedTracingConfig<Span> wingtipsDistributedTracingConfig = getOrGenerateWingtipsDistributedTracingConfig(serverConfig);
        // No custom channel initializer, so use the default
        channelInitializer = new HttpChannelInitializer(sslCtx, serverConfig.maxRequestSizeInBytes(), serverConfig.appEndpoints(), serverConfig.requestAndResponseFilters(), serverConfig.longRunningTaskExecutor(), serverConfig.riposteErrorHandler(), serverConfig.riposteUnhandledErrorHandler(), serverConfig.requestContentValidationService(), serverConfig.defaultRequestContentDeserializer(), new ResponseSender(serverConfig.defaultResponseContentSerializer(), serverConfig.errorResponseBodySerializer(), wingtipsDistributedTracingConfig), serverConfig.metricsListener(), serverConfig.defaultCompletableFutureTimeoutInMillisForNonblockingEndpoints(), serverConfig.accessLogger(), serverConfig.pipelineCreateHooks(), serverConfig.requestSecurityValidator(), serverConfig.workerChannelIdleTimeoutMillis(), serverConfig.proxyRouterConnectTimeoutMillis(), serverConfig.incompleteHttpCallTimeoutMillis(), serverConfig.maxOpenIncomingServerChannels(), serverConfig.isDebugChannelLifecycleLoggingEnabled(), serverConfig.userIdHeaderKeys(), serverConfig.responseCompressionThresholdBytes(), serverConfig.httpRequestDecoderConfig(), wingtipsDistributedTracingConfig);
    }
    // Create the server bootstrap
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(channelClass).childHandler(channelInitializer);
    // execute pre startup hooks
    List<@NotNull PreServerStartupHook> preServerStartupHooks = serverConfig.preServerStartupHooks();
    if (preServerStartupHooks != null) {
        for (PreServerStartupHook hook : preServerStartupHooks) {
            hook.executePreServerStartupHook(b);
        }
    }
    if (serverConfig.isDebugChannelLifecycleLoggingEnabled())
        b.handler(new LoggingHandler(SERVER_BOSS_CHANNEL_DEBUG_LOGGER_NAME, LogLevel.DEBUG));
    // Bind the server to the desired port and start it up so it is ready to receive requests
    Channel ch = b.bind(port).sync().channel();
    // execute post startup hooks
    List<@NotNull PostServerStartupHook> postServerStartupHooks = serverConfig.postServerStartupHooks();
    if (postServerStartupHooks != null) {
        for (PostServerStartupHook hook : postServerStartupHooks) {
            hook.executePostServerStartupHook(serverConfig, ch);
        }
    }
    channels.add(ch);
    logger.info("Server channel open and accepting " + (serverConfig.isEndpointsUseSsl() ? "https" : "http") + " requests on port " + port);
    startedUp = true;
    // Add a shutdown hook so we can gracefully stop the server when the JVM is going down
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            shutdown();
        } catch (Exception e) {
            logger.warn("Error shutting down Riposte", e);
            throw new RuntimeException(e);
        }
    }));
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) Span(com.nike.wingtips.Span) ResponseSender(com.nike.riposte.server.http.ResponseSender) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) HttpChannelInitializer(com.nike.riposte.server.channelpipeline.HttpChannelInitializer) PostServerStartupHook(com.nike.riposte.server.hooks.PostServerStartupHook) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) PreServerStartupHook(com.nike.riposte.server.hooks.PreServerStartupHook)

Aggregations

ServerBootstrap (io.netty.bootstrap.ServerBootstrap)448 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)246 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)239 Channel (io.netty.channel.Channel)187 ChannelFuture (io.netty.channel.ChannelFuture)183 EventLoopGroup (io.netty.channel.EventLoopGroup)168 Bootstrap (io.netty.bootstrap.Bootstrap)134 SocketChannel (io.netty.channel.socket.SocketChannel)126 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)115 InetSocketAddress (java.net.InetSocketAddress)113 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)98 ChannelPipeline (io.netty.channel.ChannelPipeline)88 LoggingHandler (io.netty.handler.logging.LoggingHandler)82 LocalServerChannel (io.netty.channel.local.LocalServerChannel)76 LocalChannel (io.netty.channel.local.LocalChannel)73 CountDownLatch (java.util.concurrent.CountDownLatch)66 Test (org.junit.jupiter.api.Test)66 LocalAddress (io.netty.channel.local.LocalAddress)61 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)60 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)57