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


Java ChannelFutureListener类代码示例

本文整理汇总了Java中io.netty.channel.ChannelFutureListener的典型用法代码示例。如果您正苦于以下问题:Java ChannelFutureListener类的具体用法?Java ChannelFutureListener怎么用?Java ChannelFutureListener使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: writeBack

import io.netty.channel.ChannelFutureListener; //导入依赖的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

示例2: checkProducerTransactionState

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
public void checkProducerTransactionState(
    final Channel channel,
    final CheckTransactionStateRequestHeader requestHeader,
    final SelectMappedBufferResult selectMappedBufferResult) {
    RemotingCommand request =
        RemotingCommand.createRequestCommand(RequestCode.CHECK_TRANSACTION_STATE, requestHeader);
    request.markOnewayRPC();

    try {
        FileRegion fileRegion =
            new OneMessageTransfer(request.encodeHeader(selectMappedBufferResult.getSize()),
                selectMappedBufferResult);
        channel.writeAndFlush(fileRegion).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                selectMappedBufferResult.release();
                if (!future.isSuccess()) {
                    log.error("invokeProducer failed,", future.cause());
                }
            }
        });
    } catch (Throwable e) {
        log.error("invokeProducer exception", e);
        selectMappedBufferResult.release();
    }
}
 
开发者ID:lyy4j,项目名称:rmq4note,代码行数:27,代码来源:Broker2Client.java

示例3: rebind

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
/**
 * Reopens the listening channel for this node. If the channel was already open, has no effect and
 * future completes immediately.
 *
 * @return future that completes when listening channel is reopened.
 */
private CompletableFuture<Void> rebind() {
  if (this.channel.get().isOpen()) {
    // already accepting...
    return CompletableFuture.completedFuture(null);
  }
  CompletableFuture<Void> future = new CompletableFuture<>();
  ChannelFuture bindFuture = bootstrap.bind(this.getAddress());
  bindFuture.addListener(
      (ChannelFutureListener)
          channelFuture -> {
            if (channelFuture.isSuccess()) {
              channelFuture.channel().attr(Server.HANDLER).set(this);
              logger.debug("Bound {} to {}", BoundNode.this, channelFuture.channel());
              future.complete(null);
              channel.set(channelFuture.channel());
            } else {
              // If failed, propagate it.
              future.completeExceptionally(
                  new BindNodeException(BoundNode.this, getAddress(), channelFuture.cause()));
            }
          });
  return future;
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:30,代码来源:BoundNode.java

示例4: sendHttpResponse

import io.netty.channel.ChannelFutureListener; //导入依赖的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

示例5: sendHttpResponse

import io.netty.channel.ChannelFutureListener; //导入依赖的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

示例6: closeChannelGracefully

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
static void closeChannelGracefully(InetSocketAddress udpSource) {
    Channel socksChannel = removeSocksMapping(udpSource);
    Channel udpChannel = removeUdpMapping(udpSource);
    Channel tcpChannel = removeTcpMapping(udpSource);
    if (tcpChannel.isActive()) {
        tcpChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        log.info("\t          Proxy << Target \tDisconnect");
    }
    if (socksChannel.isActive()) {
        socksChannel.close();
        log.info("\tClient << Proxy           \tDisconnect");
    }
    if (udpChannel.isActive()) {
        udpChannel.close();
    }
}
 
开发者ID:ZhangJiupeng,项目名称:AgentX,代码行数:17,代码来源:XChannelMapper.java

示例7: writeFlush

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
/**
 * Write and flush channel context
 *
 * @param close whether close http connection
 */
private void writeFlush(boolean close) {

    if (flushed()) {

        return;
    }

    setDate();
    setPowerBy();
    setResponseTime();

    if (close) {

        channelCxt.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
    } else {

        header(CONNECTION, "keep-alive");
        channelCxt.writeAndFlush(httpResponse);
    }

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

示例8: sendOutOfMemory

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
private void sendOutOfMemory(OutOfMemoryException e, final ChannelHandlerContext ctx, int coordinationId){
  final UserException uex = UserException.memoryError(e)
      .message("Out of memory while receiving data.")
      .build(logger);

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

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

  ChannelFuture future = ctx.writeAndFlush(outMessage);
  // if we were unable to report back the failure make sure we close the channel otherwise we may cause the sender
  // to block undefinitely waiting for an ACK on this message
  future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:22,代码来源:MessageDecoder.java

示例9: doStart

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
@Override
protected void doStart() {
    try {
        ChannelFuture f = bootstrap.bind(address);
        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    notifyStarted();
                } else {
                    notifyFailed(future.cause());
                }
            }
        });
    } catch (Throwable t) {
        notifyFailed(t);
        Throwables.propagate(t);
    }
}
 
开发者ID:lemonJun,项目名称:TakinRPC,代码行数:20,代码来源:RpcServer.java

示例10: onGetFileChecksum

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
private void onGetFileChecksum(ChannelHandlerContext ctx) throws IOException {
  MD5MD5CRC32FileChecksum checksum = null;
  final String nnId = params.namenodeId();
  DFSClient dfsclient = newDfsClient(nnId, conf);
  try {
    checksum = dfsclient.getFileChecksum(path, Long.MAX_VALUE);
    dfsclient.close();
    dfsclient = null;
  } finally {
    IOUtils.cleanup(LOG, dfsclient);
  }
  final byte[] js = JsonUtil.toJsonString(checksum).getBytes(Charsets.UTF_8);
  DefaultFullHttpResponse resp =
    new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(js));

  resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
  resp.headers().set(CONTENT_LENGTH, js.length);
  resp.headers().set(CONNECTION, CLOSE);
  ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:WebHdfsHandler.java

示例11: main

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
                future.channel().close();
            }
        }
    });
}
 
开发者ID:alamby,项目名称:upgradeToy,代码行数:21,代码来源:SimpleClient.java

示例12: sendMessage

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
public static void sendMessage(AbstractBinaryEncoder encoder, Channel channel, Message msg,
		Proc3<Boolean, Throwable, Channel> listener) throws MessageCodecException {
	if (channel == null) {
		Procs.invoke(listener, false, new NullPointerException("channel"), null);
		return;
	}
	if (!channel.isWritable()) {
		Procs.invoke(listener, false, new IOException(" channel " + channel.remoteAddress() + " is unwritable"),
				channel);
		return;
	}
	ByteBuf buffer = Unpooled.buffer();
	encoder.beforeWriteBody(buffer, msg.getMessageId());
	msg.buffer(buffer);
	try {
		msg.encode();
	} catch (Exception e) {
		throw new MessageCodecException(e);
	}
	msg.buffer(null);
	encoder.afterWriteBody(buffer);
	flow(msg.getClass(), buffer);
	channel.writeAndFlush(buffer).addListener((ChannelFutureListener) arg0 -> {
		Procs.invoke(listener, arg0.isSuccess(), arg0.cause(), arg0.channel());
	});
}
 
开发者ID:HankXV,项目名称:Limitart,代码行数:27,代码来源:SendMessageUtil.java

示例13: onSocksSuccess

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
private void onSocksSuccess(ChannelHandlerContext ctx, Socks5CommandRequest request) {
    Address serverAddr = new Address(request.dstAddr(), request.dstPort());
    createServerChannel(ctx, serverAddr).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ConnectionInfo newConnectionInfo = new ConnectionInfo(
                        connectionInfo.getClientAddr(), serverAddr);
                ctx.writeAndFlush(new DefaultSocks5CommandResponse(
                        Socks5CommandStatus.SUCCESS,
                        request.dstAddrType(),
                        request.dstAddr(),
                        request.dstPort()));

                onServerConnected(ctx, newConnectionInfo, future.channel());
            } else {
                ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(
                        Socks5CommandStatus.FAILURE,
                        request.dstAddrType(),
                        request.dstAddr(),
                        request.dstPort()));
                ctx.close();
            }
        }
    });
}
 
开发者ID:chhsiao90,项目名称:nitmproxy,代码行数:27,代码来源:SocksProxyHandler.java

示例14: channelRead

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
@Override
public void channelRead(final ChannelHandlerContext context, Object msg) {
    if(client.getInbound().isActive()) {
        client.getInbound().writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    context.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    } else {
        client.getOutbound().close();
    }
}
 
开发者ID:thebagchi,项目名称:heimdall-proxy,代码行数:18,代码来源:HttpServerToProxyServerHandler.java

示例15: channelRead0

import io.netty.channel.ChannelFutureListener; //导入依赖的package包/类
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object object) throws Exception {
    System.out.println("handler中exportedServices:" + exportedServices.size());
    Request request = (Request)object;
    String serviceName = request.getInterfaceName();
    String methodName = request.getMethodName();
    Class<?>[] parameterTypes = request.getParameterTypes();
    Object[] arguments = request.getArgs();
    Class serviceClass = exportedServices.get(serviceName);

    Method method = serviceClass.getMethod(methodName,parameterTypes);
    Object result = method.invoke(serviceClass.newInstance(),arguments);

    Response response = new Response();
    response.setResult(result);

    channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
 
开发者ID:dachengxi,项目名称:mini-dubbo,代码行数:18,代码来源:NettyServiceHandler.java


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