private Server( AddressResolver addressResolver, EventLoopGroup eventLoopGroup, Class<? extends ServerChannel> channelClass, boolean customEventLoop, Timer timer, boolean customTimer, long bindTimeoutInNanos, StubStore stubStore, boolean activityLogging) { this( addressResolver, eventLoopGroup, customEventLoop, timer, customTimer, bindTimeoutInNanos, stubStore, activityLogging, new ServerBootstrap() .group(eventLoopGroup) .channel(channelClass) .childHandler(new Initializer())); }
@Override public void start() { this.bossGroup = NettyUtils.createEventLoopGroup(1); this.workerGroup = NettyUtils.createEventLoopGroup(4); Class<? extends ServerChannel> serverChannelClass = NettyUtils.getServerChannelClass(); this.logger.info("I am going to start a server on {}:{}.", this.config.getServerHost(), this.config.getServerPort()); ServerBootstrap serverBootstrap = new ServerBootstrap(); try { channel = serverBootstrap .group(bossGroup, workerGroup) .channel(serverChannelClass) .childHandler(new ServerChannelInitializer(this)) .childOption(ChannelOption.SO_KEEPALIVE, true) .bind(config.getServerHost(), config.getServerPort()) .sync().channel(); } catch (InterruptedException e) { e.printStackTrace(); } this.logger.info("Started the server on {}:{}.", this.config.getServerHost(), this.config.getServerPort()); }
/** * Start proxy server * */ public void start() throws InterruptedException { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup); serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() { @Override public ServerChannel newChannel() { return new NioServerSocketChannel(); } }); serverBootstrap.childHandler(new ProxyInitializer(this)); //bind ChannelFuture future = serverBootstrap.bind(_host, _port); //wait for the future future.awaitUninterruptibly(); if (!future.isSuccess()) { future.channel().closeFuture().awaitUninterruptibly(); throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause()); } else { _allChannels.add(future.channel()); } }
@Override public boolean remove(Object o) { if (!(o instanceof Channel)) { return false; } boolean removed; Channel c = (Channel) o; if (c instanceof ServerChannel) { removed = serverChannels.remove(c); } else { removed = nonServerChannels.remove(c); } if (!removed) { return false; } c.closeFuture().removeListener(remover); return true; }
private void buildServerAndRun(EventLoopGroup bossGroup, EventLoopGroup workerGroup, Class<? extends ServerChannel> channelClass) throws Exception { ServerBootstrap b = new ServerBootstrap(); try { b.group(bossGroup, workerGroup) .channel(channelClass) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(getChannelInitializer()); InetSocketAddress listenTo = (listenAddress == null || listenAddress.isEmpty()) ? new InetSocketAddress(port) : new InetSocketAddress(listenAddress, port); this.cf = b.bind(listenTo).sync(); } catch (Exception e) { log.error("Error initializing {}, port {}", getServerName(), port, e); throw e; } log.info("{} server listening at {} port.", getServerName(), port); }
@Override public boolean remove(Object o) { Channel c = null; if (o instanceof ChannelId) { c = nonServerChannels.remove(o); if (c == null) { c = serverChannels.remove(o); } } else if (o instanceof Channel) { c = (Channel) o; if (c instanceof ServerChannel) { c = serverChannels.remove(c.id()); } else { c = nonServerChannels.remove(c.id()); } } if (c == null) { return false; } c.closeFuture().removeListener(remover); return true; }
private void doRun(EventLoopGroup loupGroup, Class<? extends ServerChannel> serverChannelClass) throws InterruptedException { try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.option(ChannelOption.SO_REUSEADDR, true); b.group(loupGroup).channel(serverChannelClass).childHandler(new HelloServerInitializer(loupGroup.next())); b.option(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE); b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)); b.childOption(ChannelOption.SO_REUSEADDR, true); b.childOption(ChannelOption.MAX_MESSAGES_PER_READ, Integer.MAX_VALUE); Channel ch = b.bind(port).sync().channel(); ch.closeFuture().sync(); } finally { loupGroup.shutdownGracefully().sync(); } }
/** * Returns a server socket channel class suitable for specified event loop group. * * @param eventLoopGroup the event loop group for which to identify an appropriate socket channel class; must not * be {@code null} * * @return a server socket channel class suitable for use with the given event loop group * * @throws IllegalArgumentException in case of null or unrecognized event loop group */ @SuppressWarnings("unchecked") static Class<? extends ServerChannel> getServerSocketChannelClass(final EventLoopGroup eventLoopGroup) { Objects.requireNonNull(eventLoopGroup); final Class<? extends ServerChannel> serverSocketChannelClass; if (eventLoopGroup instanceof NioEventLoopGroup) { serverSocketChannelClass = NioServerSocketChannel.class; } else if (eventLoopGroup instanceof OioEventLoopGroup) { serverSocketChannelClass = OioServerSocketChannel.class; } else if (EPOLL_EVENT_LOOP_GROUP_CLASS.equals(eventLoopGroup.getClass().getName())) { serverSocketChannelClass = (Class<? extends ServerChannel>) loadSocketChannelClass(EPOLL_SERVER_SOCKET_CHANNEL_CLASS); } else if (KQUEUE_EVENT_LOOP_GROUP_CLASS.equals(eventLoopGroup.getClass().getName())) { serverSocketChannelClass = (Class<? extends ServerChannel>) loadSocketChannelClass(KQUEUE_SERVER_SOCKET_CHANNEL_CLASS); } else { throw new IllegalArgumentException("Could not find server socket class for event loop group class: " + eventLoopGroup.getClass().getName()); } return serverSocketChannelClass; }
/** Returns the correct ServerSocketChannel class based on IOMode. */ public static Class<? extends ServerChannel> getServerChannelClass(IOMode mode) { switch (mode) { case NIO: return NioServerSocketChannel.class; case EPOLL: return EpollServerSocketChannel.class; default: throw new IllegalArgumentException("Unknown io mode: " + mode); } }
@Override public void start() { this.bossGroup = NettyUtils.createEventLoopGroup(1); this.workerGroup = new NioEventLoopGroup(4); Class<? extends ServerChannel> serverChannelClazz = NettyUtils.getServerChannelClass(); ChannelHandler channelHandler = new CardeaServerChannelInitializer(this.backendManager); this.logger.info("Starting backend handling tasks."); this.executorService .scheduleAtFixedRate(new CheckDeadBackendsTask(this.backendManager), 10, 10, TimeUnit.SECONDS); this.executorService .scheduleAtFixedRate(new BackendRecoverTask(this.backendManager), 10, 10, TimeUnit.SECONDS); this.logger.info("Starting server and proxying all connections on *:", this.config.getServerPort()); ServerBootstrap serverBootstrap = new ServerBootstrap(); try { serverBootstrap .channel(serverChannelClazz) .group(this.bossGroup, this.workerGroup) .childHandler(channelHandler) .childOption(ChannelOption.AUTO_READ, false) .bind(this.config.getServerPort()) .sync().channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } this.logger.info("Started reverse proxy on *:", this.config.getServerPort()); }
private void executeBootstrap(ScheduledExecutor scheduledExecutor, int port, boolean useWebSocket, boolean useSsl) throws InterruptedException { ServerBootstrap bootstrap = new ServerBootstrap(); Class<? extends ServerChannel> serverChannelClass; if (Literals.NETTY_EPOLL.equals(Settings.INSTANCE.nettyTransportMode())) { serverChannelClass = EpollServerSocketChannel.class; } else { serverChannelClass = NioServerSocketChannel.class; } bootstrap = bootstrap.group(bossGroup, workerGroup).channel(serverChannelClass); bootstrap.option(ChannelOption.TCP_NODELAY, true); if (scheduledExecutor != null) { bootstrap.handler(scheduledExecutor); } bootstrap.childHandler(new MqttChannelInitializer(useWebSocket, useSsl)); bootstrap.childOption(ChannelOption.TCP_NODELAY, true) // setting buffer size can improve I/O .childOption(ChannelOption.SO_SNDBUF, 1048576).childOption(ChannelOption.SO_RCVBUF, 1048576) // recommended in // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#11.0 .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024)) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.bind(port).sync(); }
@Override public boolean contains(Object o) { if (o instanceof Channel) { Channel c = (Channel) o; if (o instanceof ServerChannel) { return serverChannels.contains(c); } else { return nonServerChannels.contains(c); } } else { return false; } }
@Override public boolean add(Channel channel) { ConcurrentSet<Channel> set = channel instanceof ServerChannel? serverChannels : nonServerChannels; boolean added = set.add(channel); if (added) { channel.closeFuture().addListener(remover); } return added; }
/** * Starts to accept connections on local address. */ public CompletableFuture<Transport> bind0() { incomingMessagesSubject.subscribeOn(Schedulers.from(bootstrapFactory.getWorkerGroup())); // Resolve listen IP address final InetAddress listenAddress = Addressing.getLocalIpAddress(config.getListenAddress(), config.getListenInterface(), config.isPreferIPv6()); // Resolve listen port int bindPort = config.isPortAutoIncrement() ? Addressing.getNextAvailablePort(listenAddress, config.getPort(), config.getPortCount()) // Find available port : config.getPort(); // Listen address address = Address.create(listenAddress.getHostAddress(), bindPort); ServerBootstrap server = bootstrapFactory.serverBootstrap().childHandler(incomingChannelInitializer); ChannelFuture bindFuture = server.bind(listenAddress, address.port()); final CompletableFuture<Transport> result = new CompletableFuture<>(); bindFuture.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { serverChannel = (ServerChannel) channelFuture.channel(); networkEmulator = new NetworkEmulator(address, config.isUseNetworkEmulator()); networkEmulatorHandler = config.isUseNetworkEmulator() ? new NetworkEmulatorHandler(networkEmulator) : null; LOGGER.info("Bound to: {}", address); result.complete(TransportImpl.this); } else { Throwable cause = channelFuture.cause(); if (config.isPortAutoIncrement() && isAddressAlreadyInUseException(cause)) { LOGGER.warn("Can't bind to address {}, try again on different port [cause={}]", address, cause.toString()); bind0().thenAccept(result::complete); } else { LOGGER.error("Failed to bind to: {}, cause: {}", address, cause); result.completeExceptionally(cause); } } }); return result; }
ServerChannelConfiguration( EventLoopGroup bossGroup, EventLoopGroup workerGroup, Class<? extends ServerChannel> channelClass) { this.bossGroup = bossGroup; this.workerGroup = workerGroup; this.channelClass = channelClass; }
@Override public boolean contains(Object o) { if (o instanceof Channel) { Channel c = (Channel) o; if (o instanceof ServerChannel) { return serverChannels.containsValue(c); } else { return nonServerChannels.containsValue(c); } } else { return false; } }
@Override public boolean add(Channel channel) { ConcurrentMap<ChannelId, Channel> map = channel instanceof ServerChannel? serverChannels : nonServerChannels; boolean added = map.putIfAbsent(channel.id(), channel) == null; if (added) { channel.closeFuture().addListener(remover); } return added; }
/** * The {@link Class} which is used to create {@link Channel} instances from. * You either use this or {@link #channelFactory(ServerChannelFactory)} if your * {@link Channel} implementation has no no-args constructor. */ public ServerBootstrap channel(Class<? extends ServerChannel> channelClass) { if (channelClass == null) { throw new NullPointerException("channelClass"); } return channelFactory(new ServerBootstrapChannelFactory<ServerChannel>(channelClass)); }
NettyServer( SocketAddress address, Class<? extends ServerChannel> channelType, Map<ChannelOption<?>, ?> channelOptions, @Nullable EventLoopGroup bossGroup, @Nullable EventLoopGroup workerGroup, ProtocolNegotiator protocolNegotiator, List<ServerStreamTracer.Factory> streamTracerFactories, TransportTracer.Factory transportTracerFactory, int maxStreamsPerConnection, int flowControlWindow, int maxMessageSize, int maxHeaderListSize, long keepAliveTimeInNanos, long keepAliveTimeoutInNanos, long maxConnectionIdleInNanos, long maxConnectionAgeInNanos, long maxConnectionAgeGraceInNanos, boolean permitKeepAliveWithoutCalls, long permitKeepAliveTimeInNanos) { this.address = address; this.channelType = checkNotNull(channelType, "channelType"); checkNotNull(channelOptions, "channelOptions"); this.channelOptions = new HashMap<ChannelOption<?>, Object>(channelOptions); this.bossGroup = bossGroup; this.workerGroup = workerGroup; this.protocolNegotiator = checkNotNull(protocolNegotiator, "protocolNegotiator"); this.streamTracerFactories = checkNotNull(streamTracerFactories, "streamTracerFactories"); this.usingSharedBossGroup = bossGroup == null; this.usingSharedWorkerGroup = workerGroup == null; this.transportTracerFactory = transportTracerFactory; this.maxStreamsPerConnection = maxStreamsPerConnection; this.flowControlWindow = flowControlWindow; this.maxMessageSize = maxMessageSize; this.maxHeaderListSize = maxHeaderListSize; this.keepAliveTimeInNanos = keepAliveTimeInNanos; this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos; this.maxConnectionIdleInNanos = maxConnectionIdleInNanos; this.maxConnectionAgeInNanos = maxConnectionAgeInNanos; this.maxConnectionAgeGraceInNanos = maxConnectionAgeGraceInNanos; this.permitKeepAliveWithoutCalls = permitKeepAliveWithoutCalls; this.permitKeepAliveTimeInNanos = permitKeepAliveTimeInNanos; }
public static void main(String[] args) { Stopwatch watch = new Stopwatch(); watch.start(); GlydarBootstrap bootstrap = new GlydarBootstrap(args); server = new GServer(bootstrap); ParaGlydar.setServer(server); serverThread = new Thread(server); serverBootstrap = new ServerBootstrap(); serverBootstrap.childHandler(new ProtocolInitializer()) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 32 * 1024) .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 64 * 1024) .group(new NioEventLoopGroup()) .channelFactory(new ChannelFactory<ServerChannel>() { @Override public ServerChannel newChannel() { return new NioServerSocketChannel(); } }) .bind(new InetSocketAddress(server.getConfig().getPort())); server.setUpWorlds(); try { server.getPluginLoader().loadPlugins(); } catch (Exception exc) { server.getLogger().warning(exc, "Error while loading plugins"); } server.getLogger().info("Server ready on port {0}", server.getConfig().getPort()); server.getLogger().info("This server is running {0} version {1}", server.getName(), server.getVersion()); watch.stop(); server.getLogger().info("Server started in {0}ms", watch.elapsed(TimeUnit.MILLISECONDS)); server.getCommandReader().start(); serverThread.start(); }
protected SimpleServerBootstrapFactory( Class<? extends ServerChannel> serverChannelType, Map<ChannelOption<?>, ?> channelOptions, Map<ChannelOption<?>, ?> serverChannelOptions) { this.serverChannelType = serverChannelType; this.channelOptions = channelOptions; this.serverChannelOptions = serverChannelOptions; }
protected AbstractRpcServer(int port, Class<? extends ServerChannel> channelClass, EventLoopGroup parentGroup, EventLoopGroup childGroup) { this.port = port; this.channelClass = channelClass; this.parentGroup = parentGroup; this.childGroup = childGroup; }
private static Class<? extends ServerChannel> epollClass() { return io.netty.channel.epoll.EpollServerSocketChannel.class; }
public static Class<? extends ServerChannel> serverChannelType() { if (Epoll.isAvailable()) { return EpollServerSocketChannel.class; } return NioServerSocketChannel.class; }
public static Class<? extends ServerChannel> getServerChannelClass() { return EPOLL ? EpollServerSocketChannel.class : NioServerSocketChannel.class; }
public NettyServerConfig(Class<? extends ServerChannel> channelClass, EventLoopGroup boss,EventLoopGroup ioworkers) { this.channelClass = channelClass; this.boss = boss; this.ioWorkers = ioworkers; }
public Class<? extends ServerChannel> getChannelClass() { return channelClass; }
public DefaultServer(Class serverChannelClass, ChannelPipelineFactoryFactory factory, Set<String> channelOptions, int port, InetAddress address) { if (!ServerChannel.class.isAssignableFrom(serverChannelClass)) throw new RuntimeException( "serverChannelClass must implement ServerChannel"); // Configure the server. bootstrap = new ServerBootstrap(); _port = port; _address = address; internalGroup = new DefaultEventExecutorGroup(10); if (isNio(serverChannelClass)) { bossGroup = new NioEventLoopGroup(); childGroup = new NioEventLoopGroup(); } else if (isOio(serverChannelClass)) { bossGroup = new OioEventLoopGroup(); childGroup = new OioEventLoopGroup(); } else { bossGroup = new NioEventLoopGroup(); childGroup = new NioEventLoopGroup(); } bootstrap.group(bossGroup, childGroup); bootstrap.channel(serverChannelClass); // bootstrap.setOption("child.trafficClass", IPTOS_LOWDELAY); // bootstrap.setOption("child.tcpNoDelay", false); // bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_THROUGHPUT); setChannelOptions(channelOptions); bootstrap.option(ChannelOption.SO_BACKLOG, 100); ChannelPipelineFactory channelPipelineFactory = factory.create( internalGroup, bootstrap); bootstrap.childHandler(channelPipelineFactory); }
public static Class<? extends ServerChannel> serverChannelClass() { if (PlatformUtil.isLinux()) { return EpollServerSocketChannel.class; } return NioServerSocketChannel.class; }
public static Class<? extends ServerChannel> getServerChannel() { return epoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class; }
@Override Class<? extends ServerChannel> getChannelClass() { return NioServerSocketChannel.class; }
@Override public Class<? extends ServerChannel> onServerChannel(EventLoopGroup group) { return defaultLoops.onServerChannel(group); }
@Override public Class<? extends ServerChannel> getServerChannel(EventLoopGroup group) { return useEpoll(group) ? EpollServerSocketChannel.class : NioServerSocketChannel.class; }
@Override public Class<? extends ServerChannel> getServerChannel(EventLoopGroup group) { return useKQueue(group) ? KQueueServerSocketChannel.class : NioServerSocketChannel.class; }