Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener ChannelFutureListener.

Prototype

ChannelFutureListener

Source Link

Usage

From source file:net.hasor.rsf.center.server.launcher.http.HttpClient.java

License:Apache License

public BasicFuture<HttpResponse> request(String requestPath, Map<String, String> reqParams, byte[] body)
        throws Exception {
    // ?Netty//from  ww  w  .ja  va 2s.c om
    final Bootstrap b = new Bootstrap();
    final BasicFuture<HttpResponse> future = new BasicFuture<HttpResponse>();
    b.group(this.worker);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            // httpResponse??HttpResponseDecoder?
            ch.pipeline().addLast(new HttpResponseDecoder());
            // ??httprequest?HttpRequestEncoder?
            ch.pipeline().addLast(new HttpRequestEncoder());
            ch.pipeline().addLast(new ResponseRead(future));
        }
    });
    //
    // Server
    ChannelFuture f = b.connect(this.remoteHost, this.remotePort).sync();
    //
    // http
    URL reqPath = new URL("http", this.remoteHost, this.remotePort, requestPath);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            reqPath.toString());
    request.headers().set(HttpHeaders.Names.HOST, this.remoteHost);
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    //
    // ??http
    if (body != null) {
        request.content().writeBytes(body);
    }
    f.channel().write(request);
    f.channel().flush();
    //
    // 
    f.channel().closeFuture().addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture nettyFuture) throws Exception {
            future.cancel();//?
        }
    });
    return future;
}

From source file:net.hasor.rsf.remoting.transport.customer.RsfRequestManager.java

License:Apache License

/**???*/
private void sendRequest(RsfFuture rsfFuture) {
    //???/*from   w  w  w . ja va2 s.  com*/
    RsfSettings rsfSettings = this.getRsfContext().getSettings();
    if (this.requestCount.get() >= rsfSettings.getMaximumRequest()) {
        SendLimitPolicy sendPolicy = rsfSettings.getSendLimitPolicy();
        String errorMessage = "maximum number of requests, apply SendPolicy = " + sendPolicy.name();
        LoggerHelper.logWarn(errorMessage);
        if (sendPolicy == SendLimitPolicy.Reject) {
            throw new RsfException(ProtocolStatus.ClientError, errorMessage);
        } else {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    //RsfFilter
    final RsfRequestImpl request = (RsfRequestImpl) rsfFuture.getRequest();
    final RequestMsg rsfMessage = request.getMsg();
    //??
    final AbstractRsfClient rsfClient = this.getClientManager().getClient(request.getBindInfo());
    final long beginTime = System.currentTimeMillis();
    final long timeout = rsfMessage.getClientTimeout();
    //
    if (rsfClient == null) {
        rsfFuture.failed(new IllegalStateException("The lack of effective service provider."));
        return;
    }
    if (rsfClient.isActive() == false) {
        rsfFuture.failed(new IllegalStateException("client is closed."));
        return;
    }
    this.startRequest(
            rsfFuture);/* timeout ???request*/
    //
    ChannelFuture future = rsfClient.getChannel().writeAndFlush(rsfMessage);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                return;
            }
            String errorMsg = null;
            //
            if (System.currentTimeMillis() - beginTime >= timeout) {
                errorMsg = "send request too long time(" + (System.currentTimeMillis() - beginTime)
                        + "),requestID:" + rsfMessage.getRequestID();
            }
            //?
            if (future.isCancelled()) {
                errorMsg = "send request to cancelled by user,requestID:" + rsfMessage.getRequestID();
            }
            //
            if (!future.isSuccess()) {
                if (rsfClient.isActive()) {
                    // maybe some exception, so close the channel
                    getClientManager().unRegistered(rsfClient.getHostAddress());
                }
                errorMsg = "send request error " + future.cause();
            }
            LoggerHelper.logSevere(RsfRequestManager.this + ":" + errorMsg);
            //Response
            putResponse(request.getRequestID(), new RsfException(ProtocolStatus.ClientError, errorMsg));
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**  */
public void connectionTo(final InterAddress hostAddress, final BasicFuture<RsfChannel> result) {
    ///*from w  ww .  jav a 2s . c  o m*/
    //
    Bootstrap boot = new Bootstrap();
    boot.group(this.workLoopGroup);
    boot.channel(NioSocketChannel.class);
    boot.handler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    ChannelFuture future = configBoot(boot).connect(hostAddress.toSocketAddress());
    //
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                logger.error("connect to {} error.", hostAddress, future.cause());
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                logger.info("connect to {} Success.", hostAddress);
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Out));
            }
        }
    });
}

From source file:net.hasor.rsf.rpc.net.Connector.java

License:Apache License

/**
 * ??// w  w w.j a  v a  2 s.c  om
 * @param listenLoopGroup ?
 */
public void startListener(NioEventLoopGroup listenLoopGroup) {
    //
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(listenLoopGroup, this.workLoopGroup);
    boot.channel(NioServerSocketChannel.class);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelHandler[] handlerArrays = channelHandler();
            ArrayList<ChannelHandler> handlers = new ArrayList<ChannelHandler>();
            handlers.addAll(Arrays.asList(handlerArrays)); // ??
            handlers.add(Connector.this); // ?RequestInfo?ResponseInfoRSF
            //
            ch.pipeline().addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
        }
    });
    boot.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture future = configBoot(boot).bind(this.bindAddress.toSocketAddress());
    //
    final BasicFuture<RsfChannel> result = new BasicFuture<RsfChannel>();
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                future.channel().close();
                result.failed(future.cause());
            } else {
                Channel channel = future.channel();
                result.completed(new RsfChannel(protocol, bindAddress, channel, LinkType.Listener));
            }
        }
    });
    try {
        this.localListener = result.get();
        logger.info("rsf Server started at {}", this.bindAddress);
    } catch (Exception e) {
        logger.error("rsf start listener error: " + e.getMessage(), e);
        throw new RsfException(ProtocolStatus.NetworkError,
                this.bindAddress.toString() + " -> " + e.getMessage());
    }
    //
}

From source file:net.hasor.rsf.rpc.net.RsfChannel.java

License:Apache License

/**? Netty*/
private void sendData(final long requestID, Object sendData, final SendCallBack callBack) {
    if (!this.channel.isActive()) {
        RsfException e = new RsfException(ProtocolStatus.NetworkError,
                "send (" + requestID + ") an error, socket Channel is close.");
        if (callBack != null) {
            callBack.failed(requestID, e);
        }//from w  w  w  .  j  ava  2s  .  com
        return;
    }
    /*???*/
    this.sendPackets++;
    ChannelFuture future = this.channel.writeAndFlush(sendData);
    /*sendData???*/
    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                if (callBack != null) {
                    callBack.complete(requestID);
                }
                return;
            }
            lastSendTime = System.currentTimeMillis();
            RsfException e = null;
            if (future.isCancelled()) {
                //?
                String errorMsg = "send request(" + requestID + ") to cancelled by user.";
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            } else if (!future.isSuccess()) {
                //
                Throwable ex = future.cause();
                String errorMsg = "send request(" + requestID + ") an error ->" + ex.getMessage();
                e = new RsfException(ProtocolStatus.NetworkError, errorMsg, ex);
                logger.error(e.getMessage(), e);
                //Response
                if (callBack != null) {
                    callBack.failed(requestID, e);
                }
            }
        }
    });
}

From source file:net.ieldor.network.ActionSender.java

License:Open Source License

/**
 * Sends the logout to the game screen.//w  w  w.  ja  va 2s  . c o m
 */
public void sendLogout() {
    player.getChannel().write(new PacketBuf(86).toPacket()).addListener(new ChannelFutureListener() {

        /*
         * (non-Javadoc)
         * @see io.netty.channel.ChannelFutureListener#operationComplete(io.netty.channel.ChannelFuture)
         */
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            future.channel().close();
        }
    });
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> connect() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        future.complete(null);/*from  w ww  .  ja v  a 2 s  . c om*/
        return future;
    }

    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {
            sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup group = new NioEventLoopGroup(protocol.getThreads());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslContext != null) {
                pipeline.addLast(
                        sslContext.newHandler(channel.alloc(), protocol.getHost(), protocol.getPort()));
            }
            pipeline.addLast(new ObjectEncoder(),
                    new ObjectDecoder(
                            ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                    new TcpProtocolClientHandler(TcpProtocolClient.this));
        }
    });

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_LINGER, protocol.getSoLinger());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, protocol.getConnectTimeout());

    bootstrap.connect(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolClient.java

License:Apache License

@Override
public CompletableFuture<Void> close() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override//from w w w  . j  a va  2 s.  co m
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                channel = null;
                if (channelFuture.isSuccess()) {
                    future.complete(null);
                } else {
                    future.completeExceptionally(channelFuture.cause());
                }
            }
        });
    } else {
        future.complete(null);
    }
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> start() {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    // TODO: Configure proper SSL trust store.
    final SslContext sslContext;
    if (protocol.isSsl()) {
        try {//w  w w .j  av a 2s .co m
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (SSLException | CertificateException e) {
            future.completeExceptionally(e);
            return future;
        }
    } else {
        sslContext = null;
    }

    final EventLoopGroup serverGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup(protocol.getThreads());

    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(serverGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    if (sslContext != null) {
                        pipeline.addLast(sslContext.newHandler(channel.alloc()));
                    }
                    pipeline.addLast(new ObjectEncoder(),
                            new ObjectDecoder(
                                    ClassResolvers.softCachingConcurrentResolver(getClass().getClassLoader())),
                            new TcpProtocolServerHandler(TcpProtocolServer.this));
                }
            }).option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getSendBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, protocol.getSendBufferSize());
    }

    if (protocol.getReceiveBufferSize() > -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, protocol.isNoDelay());
    bootstrap.option(ChannelOption.SO_REUSEADDR, protocol.isReuseAddress());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, protocol.isKeepAlive());
    bootstrap.option(ChannelOption.SO_BACKLOG, protocol.getAcceptBacklog());

    if (protocol.getTrafficClass() > -1) {
        bootstrap.option(ChannelOption.IP_TOS, protocol.getTrafficClass());
    }

    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    bootstrap.bind(protocol.getHost(), protocol.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    workerGroup.shutdownGracefully();
                }
            });

            if (channelFuture.isSuccess()) {
                channel = channelFuture.channel();
                future.complete(null);
            } else {
                future.completeExceptionally(channelFuture.cause());
            }
        }
    });
    return future;
}

From source file:net.kuujo.copycat.netty.protocol.impl.TcpProtocolServer.java

License:Apache License

@Override
public CompletableFuture<Void> stop() {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    if (channel != null) {
        channel.close().addListener(new ChannelFutureListener() {
            @Override//from  w  w  w  .jav  a2s . c  o m
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    future.complete(null);
                } else {
                    future.completeExceptionally(channelFuture.cause());
                }
            }
        });
    } else {
        future.complete(null);
    }
    return future;
}