public void start() throws InterruptedException { final EventLoopGroup workerGroup = Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup) .channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class) .handler(new OpenCloudChannelInitializer(this)) .connect(this.host, this.port).sync().channel().closeFuture().syncUninterruptibly(); } catch (Exception ex) { if (ex.getClass().getSimpleName().equals("AnnotatedConnectException")) { System.err.println("Cannot connect to master!"); channel.close(); } else { ex.printStackTrace(); } } finally { workerGroup.shutdownGracefully(); System.out.println("Netty client stopped"); Runtime.getRuntime().halt(0); } }
protected AbstractNettyServer(String serverName) { this.serverName = Objects.requireNonNull(serverName, "server name"); bootstrap = new ServerBootstrap(); if (Epoll.isAvailable()) { bootstrap.option(ChannelOption.SO_BACKLOG, 1024).channel(EpollServerSocketChannel.class) .childOption(ChannelOption.SO_LINGER, 0).childOption(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.SO_KEEPALIVE, true); log.info(serverName + " epoll init"); } else { bootstrap.channel(NioServerSocketChannel.class); log.info(serverName + " nio init"); } bootstrap.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { initPipeline(ch.pipeline()); } }); }
public void start() throws Exception { UnknownPandaServer.getLogger().info("Loading protocol"); Protocol protocol = ProtocolSpecification.getProtocol(); protocol.load(); UnknownPandaServer.getLogger().info("Binding UniverseServer at *::" + port + " [tcp]"); this.channel = new ServerBootstrap() .group(Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup()) .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) //.childOption(ChannelOption.TCP_NODELAY, true) .childHandler(new ConnectionInitializer(this)) .localAddress("", port) .bind() .addListeners(this) .sync() .channel(); }
@Override public void init(final InetAddress address, final int port, final boolean useEpoll) { final Class<? extends ServerSocketChannel> socketChannelClass; final LazyValue<? extends EventLoopGroup> lazyInit; if ((Epoll.isAvailable()) && useEpoll) { socketChannelClass = EpollServerSocketChannel.class; lazyInit = this.epollEventLoopGroupLazyValue; CoreMain.debug("[Netty] Using epoll channel type"); } else { socketChannelClass = NioServerSocketChannel.class; lazyInit = this.nioEventLoopGroupLazyValue; CoreMain.debug("[Netty] Using default channel type"); } this.channelFuture = new ServerBootstrap().channel(socketChannelClass).childHandler(new ServerConnectionChannel(this)).group(lazyInit.get()).localAddress(address, port).bind().syncUninterruptibly(); }
@Override public void init(final InetAddress address, final int port, final boolean useEpoll) { final Class<? extends SocketChannel> socketChannelClass; final LazyValue<? extends EventLoopGroup> lazyInit; if ((Epoll.isAvailable()) && useEpoll) { socketChannelClass = EpollSocketChannel.class; lazyInit = this.epollEventLoopGroupLazyValue; CoreMain.debug("[Netty] Using epoll channel type"); } else { socketChannelClass = NioSocketChannel.class; lazyInit = this.nioEventLoopGroupLazyValue; CoreMain.debug("[Netty] Using default channel type"); } this.channelFuture = new Bootstrap().channel(socketChannelClass).handler(new ClientConnectionChannel(this)).group(lazyInit.get()).remoteAddress(address, port).connect().syncUninterruptibly(); }
public void connect(String apiKey) { Bootstrap bootstrap = new Bootstrap(); Class<? extends Channel> channelClazz; if (Epoll.isAvailable()) { channelClazz = EpollSocketChannel.class; eventLoopGroup = new EpollEventLoopGroup(); } else { channelClazz = NioSocketChannel.class; eventLoopGroup = new NioEventLoopGroup(); } bootstrap.group(eventLoopGroup) .channel(channelClazz) .option(ChannelOption.SO_KEEPALIVE, true) // TODO: add function to get data class by topic and add handler .remoteAddress(host, port) .connect(); }
@Override public void initialise(NetworkChannelHandler channelHandler) { this.channelHandler = channelHandler; final boolean useEpoll = this.configuration.getBoolean("epoll") && Epoll.isAvailable(); EventLoopGroup acceptGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("acceptGroup")) : new NioEventLoopGroup(this.configuration.getInt("acceptGroup")); EventLoopGroup ioGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("ioGroup")) : new NioEventLoopGroup(this.configuration.getInt("ioGroup")); EventLoopGroup channelGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("channelGroup")) : new NioEventLoopGroup(this.configuration.getInt("channelGroup")); this.serverBootstrap = new ServerBootstrap() .group(acceptGroup, ioGroup) .channel(useEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .childHandler(new ChannelInitialiser(channelGroup, this.channelHandler, null)) .option(ChannelOption.SO_BACKLOG, this.configuration.getInt("backlog")) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT) .childOption(ChannelOption.TCP_NODELAY, this.configuration.getBoolean("tcpNoDelay")) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); }
public McpeOverRakNetNetworkListener(VoxelwindServer voxelwindServer, String host, int port, boolean useSoReuseport) { this.server = voxelwindServer; this.address = new InetSocketAddress(host, port); this.useSoReuseport = useSoReuseport; if (Epoll.isAvailable()) { bootstrap = new Bootstrap() .channel(EpollDatagramChannel.class) .group(new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build())) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .handler(this); if (useSoReuseport) { bootstrap.option(EpollChannelOption.SO_REUSEPORT, true); } } else { bootstrap = new Bootstrap() .channel(NioDatagramChannel.class) .group(new NioEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build())) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .handler(this); } }
@Override public boolean bind() { ChannelFuture future = new ServerBootstrap() .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .group(group) .childHandler(this) .bind(server.getConfiguration().getRcon().getHost(), server.getConfiguration().getRcon().getPort()) .awaitUninterruptibly(); if (future.isSuccess()) { this.channel = future.channel(); return true; } return false; }
public static void main(String... args) throws Exception { // RakNet doesn't really like IPv6 ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED); System.setProperty("java.net.preferIPv4Stack", "true"); // Load native libraries early. boolean partiallySupportedLinux = Epoll.isAvailable(); boolean fullySupportedLinux = NativeCodeFactory.cipher.load(); if (partiallySupportedLinux) { NativeCodeFactory.zlib.load(); if (fullySupportedLinux) { NativeCodeFactory.hash.load(); } else { LOGGER.warn("You are running x64 Linux, but you are not using a fully-supported distribution. Server throughput and performance will be affected. Visit https://wiki.voxelwind.com/why_linux for more information."); } } else { LOGGER.warn("You are not running x64 Linux. Server throughput and performance will be affected. Visit https://wiki.voxelwind.com/why_linux for more information."); } VoxelwindServer server = new VoxelwindServer(); server.boot(); }
/** * Initializes the network server. * * @param address The address to bind the server to * @param useEpollWhenAvailable Whether you want to use epoll if it's available * @return The channel future */ public final ChannelFuture init(SocketAddress address, boolean useEpollWhenAvailable) { if (this.initialized) { throw new IllegalStateException("The network server can only be initialized once."); } boolean epoll = false; if (epollAvailabilityLogged) { epoll = Epoll.isAvailable() && useEpollWhenAvailable; } else if (useEpollWhenAvailable) { if (Epoll.isAvailable()) { epoll = true; Lantern.getLogger().info("Epoll is enabled."); } else { // Debug the reason why it is unavailable Lantern.getLogger().debug("Epoll is unavailable.", Epoll.unavailabilityCause()); } epollAvailabilityLogged = true; } final ChannelFuture future = init0(address, epoll); this.initialized = true; return future; }
private synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) { final ServerBootstrap serverBootstrap = new ServerBootstrap(); if (Epoll.isAvailable()) { serverBootstrap.channel(EpollServerSocketChannel.class); serverBootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } else { serverBootstrap.channel(NioServerSocketChannel.class); } final ChannelHandler serverChannelHandler = BGPChannel.createServerChannelHandler(initializer); serverBootstrap.childHandler(serverChannelHandler); serverBootstrap.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE); serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); serverBootstrap.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, WATER_MARK); // Make sure we are doing round-robin processing serverBootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(FIX_BUFFER_SIZE)); if (serverBootstrap.config().group() == null) { serverBootstrap.group(this.bossGroup, this.workerGroup); } return serverBootstrap; }
@Before public void setUp() throws BGPDocumentedException { if (!Epoll.isAvailable()) { this.boss = new NioEventLoopGroup(); this.worker = new NioEventLoopGroup(); } this.registry = new StrictBGPPeerRegistry(); this.clientListener = new SimpleSessionListener(); this.serverListener = new SimpleSessionListener(); final BGPExtensionProviderContext ctx = ServiceLoaderBGPExtensionProviderContext.getSingletonInstance(); this.serverDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker, this.registry); this.clientAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(); final IpAddress clientPeerIp = new IpAddress(new Ipv4Address(this.clientAddress.getAddress().getHostAddress())); this.registry.addPeer(clientPeerIp, this.clientListener, createPreferences(this.clientAddress)); this.clientDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker, this.registry); }
public static NetworkManager func_181124_a(InetAddress p_181124_0_, int p_181124_1_, boolean p_181124_2_) { final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); Class <? extends SocketChannel > oclass; LazyLoadBase <? extends EventLoopGroup > lazyloadbase; if (Epoll.isAvailable() && p_181124_2_) { oclass = EpollSocketChannel.class; lazyloadbase = field_181125_e; } else { oclass = NioSocketChannel.class; lazyloadbase = CLIENT_NIO_EVENTLOOP; } ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>() { protected void initChannel(Channel p_initChannel_1_) throws Exception { try { p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); } catch (ChannelException var3) { ; } p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder", (ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder", (ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager); } })).channel(oclass)).connect(p_181124_0_, p_181124_1_).syncUninterruptibly(); return networkmanager; }
public static OAuthNetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport, OAuthCallback callback) { final OAuthNetworkManager networkmanager = new OAuthNetworkManager(EnumPacketDirection.CLIENTBOUND, callback); Class<? extends SocketChannel> oclass; LazyLoadBase<? extends EventLoopGroup> lazyloadbase; if (Epoll.isAvailable() && useNativeTransport) { oclass = EpollSocketChannel.class; lazyloadbase = CLIENT_EPOLL_EVENTLOOP; } else { oclass = NioSocketChannel.class; lazyloadbase = CLIENT_NIO_EVENTLOOP; } (new Bootstrap()).group(lazyloadbase.getValue()).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel p_initChannel_1_) throws Exception { try { p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); } catch (ChannelException var3) { ; } p_initChannel_1_.pipeline().addLast("timeout", new ReadTimeoutHandler(30)) .addLast("splitter", new NettyVarint21FrameDecoder()) .addLast("decoder", new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND)) .addLast("prepender", new NettyVarint21FrameEncoder()) .addLast("encoder", new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND)) .addLast("packet_handler", networkmanager); } }).channel(oclass).connect(address, serverPort).syncUninterruptibly(); return networkmanager; }
/** * Create a new NetworkManager from the server host and connect it to the server */ public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport) { final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); Class <? extends SocketChannel > oclass; LazyLoadBase <? extends EventLoopGroup > lazyloadbase; if (Epoll.isAvailable() && useNativeTransport) { oclass = EpollSocketChannel.class; lazyloadbase = CLIENT_EPOLL_EVENTLOOP; } else { oclass = NioSocketChannel.class; lazyloadbase = CLIENT_NIO_EVENTLOOP; } ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>() { protected void initChannel(Channel p_initChannel_1_) throws Exception { try { p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); } catch (ChannelException var3) { ; } p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager); } })).channel(oclass)).connect(address, serverPort).syncUninterruptibly(); return networkmanager; }
/** * Create a new NetworkManager from the server host and connect it to the server */ @SideOnly(Side.CLIENT) public static NetworkManager createNetworkManagerAndConnect(InetAddress address, int serverPort, boolean useNativeTransport) { final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); Class <? extends SocketChannel > oclass; LazyLoadBase <? extends EventLoopGroup > lazyloadbase; if (Epoll.isAvailable() && useNativeTransport) { oclass = EpollSocketChannel.class; lazyloadbase = CLIENT_EPOLL_EVENTLOOP; } else { oclass = NioSocketChannel.class; lazyloadbase = CLIENT_NIO_EVENTLOOP; } ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>() { protected void initChannel(Channel p_initChannel_1_) throws Exception { try { p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); } catch (ChannelException var3) { ; } p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder", (ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender", (ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder", (ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler", (ChannelHandler)networkmanager); } })).channel(oclass)).connect(address, serverPort).syncUninterruptibly(); return networkmanager; }
/** * Initializes this socket and binds its internal udp socket to a free port. * If the socket is already initialized any invocation of this method will * result in an IllegalStateException. * * @throws SocketException Thrown in case the socket could not be initialized */ public void initialize() throws SocketException { if ( this.isInitialized() ) { throw new IllegalStateException( "Cannot re-initialized ClientSocket" ); } this.udpSocket = new Bootstrap(); this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() ); this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class ); this.udpSocket.handler( new ChannelInboundHandlerAdapter() { @Override public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception { io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg; PacketBuffer content = new PacketBuffer( packet.content() ); InetSocketAddress sender = packet.sender(); if ( !receiveDatagram( sender, content ) ) { // Push datagram to update queue: handleDatagram( sender, content, System.currentTimeMillis() ); } } } ); try { this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000, 65000 ) ).sync().channel(); } catch ( InterruptedException e ) { SocketException exception = new SocketException( "Could not bind to socket" ); exception.initCause( e ); throw exception; } this.afterInitialize(); }
public void initialize(String host, int port) { this.host = host; this.port = port; // bootstrap = new Bootstrap(); if (Epoll.isAvailable()) { this.childGroup = new EpollEventLoopGroup(cThreadCount); this.bootstrap.group(childGroup).channel(EpollSocketChannel.class); } else { this.childGroup = new NioEventLoopGroup(cThreadCount); this.bootstrap.group(childGroup).channel(NioSocketChannel.class); } // handlers this.prepender = new LengthFieldPrepender(this.lengthFieldLength, false); bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ClientContext.this.initChannel(ch); } }); // this.defaultOptions(); if (!options.isEmpty()) { for (Map.Entry<ChannelOption<Object>, Object> entry : options.entrySet()) { bootstrap.option(entry.getKey(), entry.getValue()); } } }
/** * 初始化 * * @param pThreadCount parent thread count. * @param cThreadCount worker thread count. * @param options netty network options。 */ public void initialize(int pThreadCount, int cThreadCount, Map<ChannelOption<Object>, Object> options) { this.bootstrap = new ServerBootstrap(); if (Epoll.isAvailable()) { this.parentGroup = new EpollEventLoopGroup(pThreadCount); this.childGroup = new EpollEventLoopGroup(cThreadCount); this.bootstrap.group(parentGroup, childGroup).channel(EpollServerSocketChannel.class); } else { this.parentGroup = new NioEventLoopGroup(pThreadCount); this.childGroup = new NioEventLoopGroup(cThreadCount); this.bootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class); } // handlers this.prepender = new LengthFieldPrepender(this.lengthFieldLength, false); bootstrap.childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ServerContext.this.initChannel(ch); } }); // this.defaultOptions(); if (!options.isEmpty()) { for (Map.Entry<ChannelOption<Object>, Object> entry : options.entrySet()) { bootstrap.childOption(entry.getKey(), entry.getValue()); } } }
/** * Starts the server. */ public void start() { loadAndPrintBanner(); try { InetSocketAddress bindAddress = serverInitializer.getBindAddress(); ServerBootstrap serverBootstrap = Epoll.isAvailable() ? newEpoolServerBootstrap() : newNioServerBootstrap(); ChannelFuture channelFuture = serverBootstrap //.handler(new LoggingHandler(LogLevel.INFO)) .childHandler(serverInitializer) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .bind(bindAddress) .sync(); LOGGER.info("Application is running at - {}://{}", (serverInitializer.isSslConfigured() ? "https" : "http"), bindAddress); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { throw new ServerException("Could not start the server", e); } finally { stop(); } }
/** * @return an EventLoopGroup suitable for the current platform */ public static EventLoopGroup newEventLoopGroup(int nThreads, ThreadFactory threadFactory) { if (Epoll.isAvailable()) { return new EpollEventLoopGroup(nThreads, threadFactory); } else { // Fallback to NIO return new NioEventLoopGroup(nThreads, threadFactory); } }
/** * <p>A factory method that manufactures {@link EventLoopGroup} based on {@link ChannelType}. If the platform * supports * Epoll and the channel type is NIO, it will return {@link EpollEventLoopGroup} instead.</p> * * @param type * The {@link ChannelType} that will determine which {@link EventLoopGroup} will be returned. * * @return The concrete {@link EventLoopGroup} instance that will be used by the transport. */ private EventLoopGroup createEventLoopGroup(ChannelType type) { switch (type) { case NIO_TCP: case NIO_UDP: if (Epoll.isAvailable()) { log.debug("Using EpollEventLoopGroup"); return new EpollEventLoopGroup(8, executorService, DefaultSelectStrategyFactory.INSTANCE); } return new NioEventLoopGroup(8, executorService, SelectorProvider.provider(), DefaultSelectStrategyFactory.INSTANCE); } return null; }
@Override public void configure(NetworkChannelHandler handler) { this.handler = handler; final boolean useEpoll = Epoll.isAvailable() && this.configuration.getBoolean("epoll"); this.eventLoopGroup = useEpoll ? new EpollEventLoopGroup(this.configuration.getInt("threads")) : new NioEventLoopGroup(this.configuration.getInt("threads")); bootstrap.group(this.eventLoopGroup); bootstrap.channel(useEpoll ? EpollSocketChannel.class : NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); }
public ServerBootstrap newServerBootstrap(int acceptor, int ioThread) throws IllegalArgumentException { if (acceptor < 0 || ioThread < 0) { throw new IllegalArgumentException("acceptor/ioThread number < 0"); } if (Epoll.isAvailable()) { logger.info("Platform is {}, use EpollEventLoopGroup", System.getProperties().getProperty("os.name")); return newEpollServerBootstrap(acceptor, ioThread); } logger.info("Platform is {}, use NioEventLoopGroup", System.getProperties().getProperty("os.name")); return newNioServerBootstrap(acceptor, ioThread); }
/** * Determine if native Epoll for netty is available * @return */ protected boolean isEpollSupported() { final boolean available = Epoll.isAvailable(); if (available) { log.info("Using native epoll"); } return available; }
HttpServer(Set<HttpService> httpServicePlugins, Set<WebSocketService> websocketServices, Swagger swagger, EventLoopGroup eventLoopGroup, List<PreprocessorEntry> preProcessors, ImmutableList<PostProcessorEntry> postProcessors, ObjectMapper mapper, Map<Class, PrimitiveType> overriddenMappings, HttpServerBuilder.ExceptionHandler exceptionHandler, Map<String, IRequestParameterFactory> customParameters, BiConsumer<Method, Operation> swaggerOperationConsumer, boolean useEpoll, boolean proxyProtocol, long maximumBodySize) { this.routeMatcher = new RouteMatcher(); this.preProcessors = preProcessors; this.workerGroup = requireNonNull(eventLoopGroup, "eventLoopGroup is null"); this.swagger = requireNonNull(swagger, "swagger is null"); this.mapper = mapper; this.customParameters = customParameters; this.swaggerOperationConsumer = swaggerOperationConsumer; this.uncaughtExceptionHandler = exceptionHandler == null ? (t, e) -> { } : exceptionHandler; this.postProcessors = postProcessors; this.proxyProtocol = proxyProtocol; this.maximumBodySize = maximumBodySize; this.bossGroup = useEpoll ? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1); registerEndPoints(requireNonNull(httpServicePlugins, "httpServices is null"), overriddenMappings); registerWebSocketPaths(requireNonNull(websocketServices, "webSocketServices is null")); routeMatcher.add(GET, "/api/swagger.json", this::swaggerApiHandle); this.useEpoll = useEpoll && Epoll.isAvailable(); this.processingRequests = new ConcurrentHashMap<>(); }
public HttpServer build() { if (eventLoopGroup == null) { eventLoopGroup = useEpoll ? new EpollEventLoopGroup() : new NioEventLoopGroup(); } if (swagger == null) { swagger = new Swagger(); } if (websocketServices == null) { websocketServices = ImmutableSet.of(); } if (customRequestParameters == null) { customRequestParameters = ImmutableMap.of(); } return new HttpServer( httpServices, websocketServices, swagger, eventLoopGroup, jsonRequestPreprocessors.build(), postProcessorEntryBuilder.build(), mapper == null ? HttpServer.DEFAULT_MAPPER : mapper, overridenMappings, exceptionHandler, customRequestParameters, swaggerOperationConsumer, useEpoll && Epoll.isAvailable(), proxyProtocol, maximumBodySize); }
private TransportTypeHolder(int workerThreads) { if (Epoll.isAvailable()) { log.info("Using native epoll transport."); bossGroup = new EpollEventLoopGroup(1); workerGroup = new EpollEventLoopGroup(workerThreads); channelClass = EpollServerSocketChannel.class; } else { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(workerThreads); channelClass = NioServerSocketChannel.class; } }
public NodeHealthCheck(int workerPoolSize) { if (Epoll.isAvailable()) { epollEventLoop = new EpollEventLoopGroup(workerPoolSize); nioEventLoop = null; } else { epollEventLoop = null; nioEventLoop = new NioEventLoopGroup(workerPoolSize); } }
public static ServerBootstrap createServerBootstrap( @Nonnull final BmpSessionFactory sessionFactory, @Nonnull final BmpHandlerFactory hf, @Nonnull final BmpSessionListenerFactory slf, @Nonnull CreateChannel createChannel, @Nonnull final EventLoopGroup bossGroup, @Nonnull final EventLoopGroup workerGroup, @Nonnull final KeyMapping keys, boolean tryEpollSocket) { final ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.childHandler(createChannel.create(sessionFactory, hf, slf)); serverBootstrap.option(ChannelOption.SO_BACKLOG, MAX_CONNECTIONS_COUNT); serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); serverBootstrap.group(bossGroup, workerGroup); if (!tryEpollSocket) { serverBootstrap.channel(NioServerSocketChannel.class); } else { if (Epoll.isAvailable()) { serverBootstrap.channel(EpollServerSocketChannel.class); } else { serverBootstrap.channel(NioServerSocketChannel.class); } if (!keys.isEmpty()) { if (Epoll.isAvailable()) { serverBootstrap.option(EpollChannelOption.TCP_MD5SIG, keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } } return serverBootstrap; }
public BmpDispatcherImpl(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final BmpMessageRegistry registry, final BmpSessionFactory sessionFactory) { if (Epoll.isAvailable()) { this.bossGroup = new EpollEventLoopGroup(); this.workerGroup = new EpollEventLoopGroup(); } else { this.bossGroup = requireNonNull(bossGroup); this.workerGroup = requireNonNull(workerGroup); } this.hf = new BmpHandlerFactory(requireNonNull(registry)); this.sessionFactory = requireNonNull(sessionFactory); }
@Override public synchronized void close() { this.close = true; if (Epoll.isAvailable()) { this.workerGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS); this.bossGroup.shutdownGracefully(0, TIMEOUT, TimeUnit.SECONDS); } }
public PCCDispatcherImpl(@Nonnull final MessageRegistry registry) { if (Epoll.isAvailable()) { this.workerGroup = new EpollEventLoopGroup(); } else { this.workerGroup = new NioEventLoopGroup(); } this.factory = new PCEPHandlerFactory(registry); }
private static void setChannelFactory(final Bootstrap bootstrap, final KeyMapping keys) { if (Epoll.isAvailable()) { bootstrap.channel(EpollSocketChannel.class); bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } else { bootstrap.channel(NioSocketChannel.class); } if (!keys.isEmpty()) { if (Epoll.isAvailable()) { bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } }
/** * Creates an instance of PCEPDispatcherImpl, gets the default selector and opens it. * * @param registry a message registry * @param negotiatorFactory a negotiation factory * @param bossGroup accepts an incoming connection * @param workerGroup handles the traffic of accepted connection */ public PCEPDispatcherImpl(@Nonnull final MessageRegistry registry, @Nonnull final PCEPSessionNegotiatorFactory<PCEPSessionImpl> negotiatorFactory, @Nonnull final EventLoopGroup bossGroup, @Nonnull final EventLoopGroup workerGroup) { this.snf = requireNonNull(negotiatorFactory); this.hf = new PCEPHandlerFactory(registry); if (Epoll.isAvailable()) { this.bossGroup = new EpollEventLoopGroup(); this.workerGroup = new EpollEventLoopGroup(); } else { this.bossGroup = requireNonNull(bossGroup); this.workerGroup = requireNonNull(workerGroup); } this.executor = requireNonNull(GlobalEventExecutor.INSTANCE); }
synchronized ServerBootstrap createServerBootstrap(final ChannelPipelineInitializer initializer) { final ServerBootstrap b = new ServerBootstrap(); b.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel ch) { initializer.initializeChannel(ch, new DefaultPromise<>(PCEPDispatcherImpl.this.executor)); } }); b.option(ChannelOption.SO_BACKLOG, SOCKET_BACKLOG_SIZE); b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (Epoll.isAvailable()) { b.channel(EpollServerSocketChannel.class); b.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } else { b.channel(NioServerSocketChannel.class); } if (!this.keys.isEmpty()) { if (Epoll.isAvailable()) { b.option(EpollChannelOption.TCP_MD5SIG, this.keys); } else { throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause()); } } // Make sure we are doing round-robin processing b.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1)); if (b.config().group() == null) { b.group(this.bossGroup, this.workerGroup); } return b; }