Search in sources :

Example 31 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener 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 32 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project scalecube by scalecube.

the class TransportImpl method connect.

private ChannelFuture connect(Address address) {
    OutgoingChannelInitializer channelInitializer = new OutgoingChannelInitializer(address);
    Bootstrap client = bootstrapFactory.clientBootstrap().handler(channelInitializer);
    ChannelFuture connectFuture = client.connect(address.host(), address.port());
    // Register logger and cleanup listener
    connectFuture.addListener((ChannelFutureListener) channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.debug("Connected from {} to {}: {}", TransportImpl.this.address, address, channelFuture.channel());
        } else {
            LOGGER.warn("Failed to connect from {} to {}", TransportImpl.this.address, address);
            outgoingChannels.remove(address);
        }
    });
    return connectFuture;
}
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) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 33 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener 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 34 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project alien4cloud by alien4cloud.

the class StompConnection method init.

@SneakyThrows({ InterruptedException.class, URISyntaxException.class })
private void init() {
    if (this.stompChannel != null) {
        throw new IllegalStateException("The stomp connection has already been started");
    }
    String wsUrl = "ws://" + host + ":" + port + endPoint + "/websocket";
    if (log.isDebugEnabled()) {
        log.debug("Web socket url {}", wsUrl);
    }
    String loginUrl = null;
    if (user != null && password != null && loginPath != null) {
        loginUrl = "http://" + host + ":" + port + loginPath;
        if (log.isDebugEnabled()) {
            log.debug("Authentication url {}", loginUrl);
        }
    }
    this.eventLoopGroup = new NioEventLoopGroup();
    this.stompClientHandler = new StompClientHandler();
    DefaultHttpHeaders handshakeHeaders = new DefaultHttpHeaders();
    if (this.headers != null) {
        for (Map.Entry<String, String> header : this.headers.entrySet()) {
            handshakeHeaders.add(header.getKey(), header.getValue());
        }
    }
    final WebSocketClientHandler webSocketHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(new URI(wsUrl), WebSocketVersion.V13, null, false, handshakeHeaders), host, user, password, loginUrl);
    Bootstrap b = new Bootstrap();
    b.group(eventLoopGroup).channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(HttpClientCodec.class.getName(), new HttpClientCodec());
            pipeline.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(8192));
            pipeline.addLast(WebSocketClientCompressionHandler.class.getName(), new WebSocketClientCompressionHandler());
            pipeline.addLast(WebSocketClientHandler.class.getName(), webSocketHandler);
            pipeline.addLast(StompSubframeDecoder.class.getName(), new StompSubframeDecoder());
            pipeline.addLast(StompSubframeEncoder.class.getName(), new StompSubframeEncoder());
            pipeline.addLast(StompSubframeAggregator.class.getName(), new StompSubframeAggregator(1048576));
            pipeline.addLast(StompClientHandler.class.getName(), stompClientHandler);
        }
    });
    this.stompChannel = b.connect(host, port).sync().channel();
    this.stompClientHandler.connectFuture(this.stompChannel.newPromise());
    webSocketHandler.handshakeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            stompClientHandler.beginStomp(stompChannel);
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) WebSocketClientCompressionHandler(io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler) StompSubframeAggregator(io.netty.handler.codec.stomp.StompSubframeAggregator) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) StompSubframeEncoder(io.netty.handler.codec.stomp.StompSubframeEncoder) URI(java.net.URI) ChannelFutureListener(io.netty.channel.ChannelFutureListener) URISyntaxException(java.net.URISyntaxException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) StompSubframeDecoder(io.netty.handler.codec.stomp.StompSubframeDecoder) Bootstrap(io.netty.bootstrap.Bootstrap) Map(java.util.Map) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SneakyThrows(lombok.SneakyThrows)

Example 35 with ChannelFutureListener

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project duangframework by tcrct.

the class RpcClient method call.

/**
 * 调用运程方法
 * @param request   rpc请求对象,封装请求的参数,参数类型等
 * @param action     rpc生产者对象,封装了生产者或者说是要调用的方法的类名,方法名,IP地址,端口等
 * @return                  处理结果 RpcResponse对象
 * @throws Exception
 */
public RpcResponse call(RpcRequest request, RpcAction action) throws Exception {
    // 这里要用内网的IP地址
    Channel channel = getChannel(action.getIntranetip(), action.getPort());
    RpcResponse response = null;
    // 先初始化一个以请求ID为KEY的响应阵列到集合中
    final String requestId = request.getRequestId();
    // 将请求结果预存到MAP中,以请求ID为key
    RESPONSE_MAP.put(requestId, new LinkedBlockingQueue<RpcResponse>(1));
    try {
        if (channel.isOpen()) {
            MessageHolder<RpcRequest> messageHolder = new MessageHolder<RpcRequest>(Protocol.REQUEST, Protocol.OK, request);
            ChannelFuture writeFuture = channel.writeAndFlush(messageHolder).sync();
            writeFuture.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    // 如果返回正常,则直接退出
                    if (future.isSuccess()) {
                        return;
                    } else {
                        String errorMsg = "Send request[" + requestId + "] to [" + future.channel().toString() + "] is error: " + future.cause().toString();
                        throw new RpcException(errorMsg);
                    }
                }
            });
        } else {
            logger.warn("channel.isClose: " + channel.remoteAddress());
        }
        response = getRpcResponse(requestId, request.getTimeout());
        if (null != response) {
            logger.warn("poll time: " + (System.currentTimeMillis() - response.getRequestStartTime()) + " ms");
        }
    } catch (Exception e) {
        response = createExceptionRpcResponse(action, e, requestId);
    } finally {
        // 无论成功与否,都必须移除集合中指定KEY的队列
        RESPONSE_MAP.remove(requestId);
    }
    return response;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) RpcException(com.duangframework.core.exceptions.RpcException) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RpcException(com.duangframework.core.exceptions.RpcException)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17