当前位置: 首页>>代码示例>>Java>>正文


Java ChannelFuture.addListener方法代码示例

本文整理汇总了Java中io.netty.channel.ChannelFuture.addListener方法的典型用法代码示例。如果您正苦于以下问题:Java ChannelFuture.addListener方法的具体用法?Java ChannelFuture.addListener怎么用?Java ChannelFuture.addListener使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.netty.channel.ChannelFuture的用法示例。


在下文中一共展示了ChannelFuture.addListener方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: completable

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
 * Convenience method to convert a {@link ChannelFuture} into a {@link CompletableFuture}
 *
 * @param future future to convert.
 * @return converted future.
 */
public static CompletableFuture<Void> completable(ChannelFuture future) {
  CompletableFuture<Void> cf = new CompletableFuture<>();
  future.addListener(
      (ChannelFutureListener)
          future1 -> {
            if (future1.isSuccess()) {
              cf.complete(null);
            } else {
              cf.completeExceptionally(future1.cause());
            }
          });
  return cf;
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:20,代码来源:ChannelUtils.java

示例2: writeBack

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
    HttpResponseStatus status;
    if (isSuccess) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    //logger.info("result str:{}", resultStr);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = channel.writeAndFlush(res);
        if (isKeepAlive) {
            HttpHeaders.setKeepAlive(res, true);
        } else {
            HttpHeaders.setKeepAlive(res, false);//set keepalive closed
            f.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e2) {
        logger.warn("Failed to send HTTP response to remote, cause by:", e2);
    }

    return content.readableBytes();
}
 
开发者ID:tiglabs,项目名称:jsf-sdk,代码行数:27,代码来源:HttpJsonHandler.java

示例3: sendHttpResponse

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
 * 返回http信息
 * @param ctx
 * @param req
 * @param res
 */
private static void sendHttpResponse(
        ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
开发者ID:ninelook,项目名称:wecard-server,代码行数:23,代码来源:NettyServerHandler.java

示例4: sendHttpResponse

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
 
开发者ID:SpreadServe,项目名称:TFWebSock,代码行数:17,代码来源:NettyHttpFileHandler.java

示例5: channelRead

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception {
    if (e instanceof ServletResponse) {
        logger.info("Handler async task...");
        HttpServletResponse response = (HttpServletResponse) e;
        Runnable task = ThreadLocalAsyncExecutor.pollTask(response);
        task.run();

        // write response...
        ChannelFuture future = ctx.channel().writeAndFlush(response);

        String keepAlive = response.getHeader(CONNECTION.toString());
        if (null != keepAlive && HttpHeaderValues.KEEP_ALIVE.toString().equalsIgnoreCase(keepAlive)) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    } else {
        ctx.fireChannelRead(e);
    }
}
 
开发者ID:geeker-lait,项目名称:tasfe-framework,代码行数:20,代码来源:AsyncHttpServletHandler.java

示例6: connect

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public synchronized ListenableFuture<Void> connect ()
{
    if ( this.connectFuture != null )
    {
        return this.connectFuture;
    }

    final ChannelFuture channelFuture = this.bootstrap.connect ( this.address );
    this.connectFuture = SettableFuture.create ();

    channelFuture.addListener ( new GenericFutureListener<ChannelFuture> () {

        @Override
        public void operationComplete ( final ChannelFuture future ) throws Exception
        {
            handleOperationComplete ( Client.this.connectFuture, future );
        }
    } );

    return this.connectFuture;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:22,代码来源:Client.java

示例7: run

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public void run(String... args) throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(group)
            .channel(NioServerSocketChannel.class)
            .childHandler(serverChannelInitializer);
    ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(30232));
    channelFuture.addListener(future -> {
        if (future.isSuccess()) {
            logger.info("「Netty」服务器启动成功");
        } else {
            logger.info("「Netty」服务器启动失败");
        }
    });
}
 
开发者ID:bitkylin,项目名称:ClusterDeviceControlPlatform,代码行数:17,代码来源:NettyServer.java

示例8: setupWithTest

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
 * Establishes a new socket connection with connection test
 */
protected void setupWithTest() {
  ChannelFuture future = boot.connect(uri.host(), port);
  future.addListener(
      new GenericFutureListener<ChannelFuture>() {

        public void operationComplete(ChannelFuture f) {
          if (f.isSuccess()) {
            channel = (HTTPChannel) f.channel();
            testConnection();
            onTestBell.promise(onConnectBell);
          } else {
            onConnectBell.ring(f.cause());
          }
        }
      });
}
 
开发者ID:SOURAVPURI100,项目名称:Stork,代码行数:20,代码来源:HTTPBuilder.java

示例9: doConnect

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public void doConnect() {
    if (channel != null && channel.isActive()) {
        return;
    }
    final TxManagerServer txManagerServer = TxManagerLocator.getInstance().locator();
    if (Objects.nonNull(txManagerServer) &&
            StringUtils.isNoneBlank(txManagerServer.getHost())
            && Objects.nonNull(txManagerServer.getPort())) {
        host = txManagerServer.getHost();
        port = txManagerServer.getPort();
    }

    ChannelFuture future = bootstrap.connect(host, port);
    LogUtil.info(LOGGER, "连接txManager-socket服务-> host:port:{}", () -> host + ":" + port);

    future.addListener((ChannelFutureListener) futureListener -> {
        if (futureListener.isSuccess()) {
            channel = futureListener.channel();
            LogUtil.info(LOGGER, "Connect to server successfully!-> host:port:{}", () -> host + ":" + port);
        } else {
            LogUtil.info(LOGGER, "Failed to connect to server, try connect after 5s-> host:port:{}", () -> host + ":" + port);
            futureListener.channel().eventLoop().schedule(this::doConnect, 5, TimeUnit.SECONDS);
        }
    });

}
 
开发者ID:yu199195,项目名称:happylifeplat-transaction,代码行数:28,代码来源:NettyClientServiceImpl.java

示例10: send500

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
 * 给客户端发送500
 *
 * @param ctx
 * @param requestId
 */
public static ChannelFuture send500(ChannelHandlerContext ctx, String requestId) {
    ResponseWrapper responseWrapper = createResponse(requestId, 500, "internal error !");
    ChannelFuture channelFuture = ctx.writeAndFlush(responseWrapper);
    channelFuture.addListener((future) -> System.out.println("send response: " + JSON.toJSONString(responseWrapper)));
    return channelFuture;
}
 
开发者ID:recklessMo,项目名称:nettyRpc,代码行数:13,代码来源:ResponseUtils.java

示例11: makeObject

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public Connection makeObject(Endpoint ep) throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 64 * 1024);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 10 * 32 * 1024);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
    bootstrap.group(clientGroup);
    // TODO: Make this faster:
    // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#37.0
    bootstrap.channel(clientChannelClass);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    if (enableNettyTls) {
        bootstrap.handler(new SslClientCommunicationChannelInitializer());
    } else {
        bootstrap.handler(new OnosCommunicationChannelInitializer());
    }
    // Start the client.
    CompletableFuture<Channel> retFuture = new CompletableFuture<>();
    ChannelFuture f = bootstrap.connect(ep.host().toString(), ep.port());

    f.addListener(future -> {
        if (future.isSuccess()) {
            retFuture.complete(f.channel());
        } else {
            retFuture.completeExceptionally(future.cause());
        }
    });
    log.debug("Established a new connection to {}", ep);
    return new Connection(retFuture);
}
 
开发者ID:shlee89,项目名称:athena,代码行数:33,代码来源:NettyMessagingManager.java

示例12: connect

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:44,代码来源:NettyWebSocketClient.java

示例13: start

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new SocksInitRequestDecoder())
                                .addLast(new SocksMessageEncoder())
                                .addLast(new Socks5Handler())
                                .addLast(Status.TRAFFIC_HANDLER);
                    }
                });
        log.info("\tStartup {}-{}-client [{}{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getMode(), config.getMode().equals("socks5") ? "" : ":" + config.getProtocol());
        new Thread(() -> new UdpServer().start()).start();
        ChannelFuture future = bootstrap.bind(config.getLocalHost(), config.getLocalPort()).sync();
        future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getLocalHost(), config.getLocalPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
开发者ID:ZhangJiupeng,项目名称:AgentX,代码行数:34,代码来源:XClient.java

示例14: sendFailure

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
private boolean sendFailure(UserRpcException e, boolean failOnAlreadySent){
  if(failOnAlreadySent){
    sendOnce();
  }else{
    if (!sent.compareAndSet(false, true)) {
      return false;
    }
  }

  UserException uex = UserException.systemError(e)
      .addIdentity(e.getEndpoint())
      .build(logger);

  OutboundRpcMessage outMessage = new OutboundRpcMessage(
      RpcMode.RESPONSE_FAILURE,
      0,
      coordinationId,
      uex.getOrCreatePBError(false)
      );

  if (RpcConstants.EXTRA_DEBUGGING) {
    logger.debug("Adding message to outbound buffer. {}", outMessage);
  }

  final ChannelFuture future = connection.getChannel().writeAndFlush(outMessage);
  // if the failure message can't be propagated, we need to close the connection to avoid having hanging messages.
  future.addListener(RESPONSE_FAILURE_FAILURE);

  // if this
  return true;
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:32,代码来源:RpcBus.java

示例15: sendFile

import io.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
 * Send response immediately for a file response
 *
 * @param raf RandomAccessFile
 */
public void sendFile(RandomAccessFile raf, long length) {

    setDate();
    setPowerBy();
    setResponseTime();
    header(CONTENT_LENGTH, Long.toString(length));

    setHttpResponse(new DefaultHttpResponse(HTTP_1_1, getStatus(), true));

    // Write initial line and headers
    channelCxt.write(httpResponse);
    // Write content
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;

    if (false /* if has ssl handler */) {

        // TODO support ssl
    } else {

        sendFileFuture = channelCxt.write(new DefaultFileRegion(raf.getChannel(), 0, length), channelCxt.newProgressivePromise());
        lastContentFuture = channelCxt.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }

    sendFileFuture.addListener(new ProgressiveFutureListener(raf));

    if (!keepAlive) {

        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }

    flush();
}
 
开发者ID:thundernet8,项目名称:Razor,代码行数:39,代码来源:Response.java


注:本文中的io.netty.channel.ChannelFuture.addListener方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。