Search in sources :

Example 1 with ServerChannel

use of io.netty.channel.ServerChannel in project tesla by linking12.

the class HttpProxyServer method doStart.

private void doStart() {
    ServerBootstrap serverBootstrap = new ServerBootstrap().group(serverGroup.getClientToProxyAcceptorPoolForTransport(), serverGroup.getClientToProxyWorkerPoolForTransport());
    ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {

        protected void initChannel(Channel ch) throws Exception {
            new ClientToProxyConnection(HttpProxyServer.this, ch.pipeline(), globalTrafficShapingHandler);
        }
    };
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {

        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(initializer);
    ChannelFuture future = serverBootstrap.bind(requestedAddress).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                registerChannel(future.channel());
            }
        }
    }).awaitUninterruptibly();
    Throwable cause = future.cause();
    if (cause != null) {
        throw new RuntimeException(cause);
    }
    this.boundAddress = ((InetSocketAddress) future.channel().localAddress());
    LOG.info("Proxy started at address: " + this.boundAddress);
    Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ClientToProxyConnection(io.github.tesla.gateway.netty.transmit.connection.ClientToProxyConnection) ServerChannel(io.netty.channel.ServerChannel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 2 with ServerChannel

use of io.netty.channel.ServerChannel in project jocean-http by isdom.

the class DefaultHttpServerBuilder method defineServer.

public Observable<? extends HttpTrade> defineServer(final SocketAddress localAddress, final Func0<Feature[]> featuresBuilder, final Feature... features) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<HttpTrade>() {

        @Override
        public void call(final Subscriber<? super HttpTrade> subscriber) {
            if (!subscriber.isUnsubscribed()) {
                final ServerBootstrap bootstrap = _creator.newBootstrap();
                final List<Channel> awaitChannels = new CopyOnWriteArrayList<>();
                bootstrap.childHandler(new Initializer() {

                    @Override
                    protected void initChannel(final Channel channel) throws Exception {
                        channel.config().setAutoRead(false);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("dump inbound channel({})'s config: \n{}", channel, Nettys.dumpChannelConfig(channel.config()));
                        }
                        if (_inboundRecvBufSize > 0) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("channel({})'s default SO_RCVBUF is {} bytes, and will be reset to {} bytes", channel, channel.config().getOption(ChannelOption.SO_RCVBUF), _inboundRecvBufSize);
                            }
                            channel.config().setOption(ChannelOption.SO_RCVBUF, _inboundRecvBufSize);
                        }
                        final Feature[] actualFeatures = JOArrays.addFirst(Feature[].class, featuresOf(featuresBuilder), features);
                        final Feature[] applyFeatures = (null != actualFeatures && actualFeatures.length > 0) ? actualFeatures : _defaultFeatures;
                        for (Feature feature : applyFeatures) {
                            if (feature instanceof FeatureOverChannelHandler) {
                                ((FeatureOverChannelHandler) feature).call(_APPLY_BUILDER, channel.pipeline());
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("initChannel with feature:{}", feature);
                                }
                            }
                        }
                        Nettys.applyHandler(channel.pipeline(), HttpHandlers.HTTPSERVER);
                        awaitInboundRequest(channel, subscriber, awaitChannels);
                    }
                });
                final ChannelFuture future = bootstrap.bind(localAddress);
                try {
                    future.sync();
                    subscriber.add(RxNettys.subscriptionForCloseChannel(future.channel()));
                    subscriber.add(Subscriptions.create(new Action0() {

                        @Override
                        public void call() {
                            while (!awaitChannels.isEmpty()) {
                                try {
                                    awaitChannels.remove(0).close();
                                } catch (Exception e) {
                                    LOG.warn("exception when remove all awaitChannels, detail: {}", ExceptionUtils.exception2detail(e));
                                }
                            }
                        }
                    }));
                    if (null != features) {
                        final ServerChannelAware serverChannelAware = serverChannelAwareOf(features);
                        if (null != serverChannelAware) {
                            serverChannelAware.setServerChannel((ServerChannel) future.channel());
                        }
                    }
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Action0(rx.functions.Action0) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ServerChannelAware(org.jocean.http.util.Nettys.ServerChannelAware) ServerChannel(io.netty.channel.ServerChannel) Feature(org.jocean.http.Feature) Observable(rx.Observable) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IOException(java.io.IOException) ChannelInitializer(io.netty.channel.ChannelInitializer) FeatureOverChannelHandler(org.jocean.http.Feature.FeatureOverChannelHandler) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 3 with ServerChannel

use of io.netty.channel.ServerChannel in project scalecube by scalecube.

the class TransportImpl method bind0.

/**
 * Helper bind method to start accepting connections on {@code listenAddress} and {@code bindPort}.
 *
 * @param bindPort bind port.
 * @param finalBindPort maximum port to bind.
 * @throws NoSuchElementException if {@code bindPort} greater than {@code finalBindPort}.
 * @throws IllegalArgumentException if {@code bindPort} doesnt belong to the range [{@link Addressing#MIN_PORT_NUMBER}
 *         .. {@link Addressing#MAX_PORT_NUMBER}].
 */
private CompletableFuture<Transport> bind0(ServerBootstrap server, InetAddress listenAddress, int bindPort, int finalBindPort) {
    incomingMessagesSubject.subscribeOn(Schedulers.from(bootstrapFactory.getWorkerGroup()));
    final CompletableFuture<Transport> result = new CompletableFuture<>();
    // Perform basic bind port validation
    if (bindPort < MIN_PORT_NUMBER || bindPort > MAX_PORT_NUMBER) {
        result.completeExceptionally(new IllegalArgumentException("Invalid port number: " + bindPort));
        return result;
    }
    if (bindPort > finalBindPort) {
        result.completeExceptionally(new NoSuchElementException("Could not find an available port from: " + bindPort + " to: " + finalBindPort));
        return result;
    }
    // Get address object and bind
    address = Address.create(listenAddress.getHostAddress(), bindPort);
    ChannelFuture bindFuture = server.bind(listenAddress, address.port());
    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(server, listenAddress, bindPort + 1, finalBindPort).thenAccept(result::complete);
            } else {
                LOGGER.error("Failed to bind to: {}, cause: {}", address, cause);
                result.completeExceptionally(cause);
            }
        }
    });
    return result;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ProtobufVarint32LengthFieldPrepender(io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) BindException(java.net.BindException) Observable(rx.Observable) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) MAX_PORT_NUMBER(io.scalecube.transport.Addressing.MAX_PORT_NUMBER) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) Schedulers(rx.schedulers.Schedulers) NoSuchElementException(java.util.NoSuchElementException) MIN_PORT_NUMBER(io.scalecube.transport.Addressing.MIN_PORT_NUMBER) Nonnull(javax.annotation.Nonnull) MessageToByteEncoder(io.netty.handler.codec.MessageToByteEncoder) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) MessageToMessageDecoder(io.netty.handler.codec.MessageToMessageDecoder) Logger(org.slf4j.Logger) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ChannelPipeline(io.netty.channel.ChannelPipeline) ServerChannel(io.netty.channel.ServerChannel) ProtobufVarint32FrameDecoder(io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder) Subject(rx.subjects.Subject) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelHandler(io.netty.channel.ChannelHandler) PublishSubject(rx.subjects.PublishSubject) CheckForNull(javax.annotation.CheckForNull) CompletableFuture(java.util.concurrent.CompletableFuture) ServerChannel(io.netty.channel.ServerChannel) NoSuchElementException(java.util.NoSuchElementException)

Example 4 with ServerChannel

use of io.netty.channel.ServerChannel in project scalecube by scalecube.

the class NettyServerTransport method bind0.

private CompletableFuture<NettyServerTransport> bind0(InetAddress bindAddress, int bindPort, int finalBindPort) {
    CompletableFuture<NettyServerTransport> result = new CompletableFuture<>();
    // Perform basic bind port validation
    if (bindPort < MIN_PORT_NUMBER || bindPort > MAX_PORT_NUMBER) {
        result.completeExceptionally(new IllegalArgumentException("Invalid port number: " + bindPort));
        return result;
    }
    if (bindPort > finalBindPort) {
        result.completeExceptionally(new NoSuchElementException("Could not find an available port from: " + bindPort + " to: " + finalBindPort));
        return result;
    }
    // Start binding
    ChannelFuture bindFuture = serverBootstrap.bind(bindAddress, bindPort);
    bindFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            NettyServerTransport.this.init(bindAddress, bindPort, (ServerChannel) channelFuture.channel());
            result.complete(NettyServerTransport.this);
        } else {
            Throwable cause = channelFuture.cause();
            if (config.isPortAutoIncrement() && isAddressAlreadyInUseException(cause)) {
                bind0(bindAddress, bindPort + 1, finalBindPort).thenAccept(result::complete);
            } else {
                result.completeExceptionally(cause);
            }
        }
    });
    return result;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelContext(io.scalecube.streams.ChannelContext) Address(io.scalecube.transport.Address) Addressing(io.scalecube.transport.Addressing) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletableFuture(java.util.concurrent.CompletableFuture) BindException(java.net.BindException) ServerChannel(io.netty.channel.ServerChannel) ChannelFuture(io.netty.channel.ChannelFuture) ConcurrentMap(java.util.concurrent.ConcurrentMap) ListeningServerStream(io.scalecube.streams.ListeningServerStream) InetAddress(java.net.InetAddress) Consumer(java.util.function.Consumer) MAX_PORT_NUMBER(io.scalecube.transport.Addressing.MAX_PORT_NUMBER) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Optional(java.util.Optional) NoSuchElementException(java.util.NoSuchElementException) MIN_PORT_NUMBER(io.scalecube.transport.Addressing.MIN_PORT_NUMBER) CompletableFuture(java.util.concurrent.CompletableFuture) ServerChannel(io.netty.channel.ServerChannel) NoSuchElementException(java.util.NoSuchElementException)

Example 5 with ServerChannel

use of io.netty.channel.ServerChannel in project netty by netty.

the class DefaultChannelGroup method remove.

@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;
}
Also used : ServerChannel(io.netty.channel.ServerChannel) Channel(io.netty.channel.Channel) ChannelId(io.netty.channel.ChannelId) ServerChannel(io.netty.channel.ServerChannel)

Aggregations

ServerChannel (io.netty.channel.ServerChannel)14 Channel (io.netty.channel.Channel)10 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)8 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)6 ChannelFuture (io.netty.channel.ChannelFuture)5 EventLoopGroup (io.netty.channel.EventLoopGroup)5 InetSocketAddress (java.net.InetSocketAddress)5 Bootstrap (io.netty.bootstrap.Bootstrap)4 ByteBuf (io.netty.buffer.ByteBuf)4 ChannelFutureListener (io.netty.channel.ChannelFutureListener)4 LocalServerChannel (io.netty.channel.local.LocalServerChannel)4 ChannelInitializer (io.netty.channel.ChannelInitializer)3 LocalAddress (io.netty.channel.local.LocalAddress)3 IOException (java.io.IOException)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)2 MAX_PORT_NUMBER (io.scalecube.transport.Addressing.MAX_PORT_NUMBER)2 MIN_PORT_NUMBER (io.scalecube.transport.Addressing.MIN_PORT_NUMBER)2