java类org.jboss.netty.channel.ChannelFutureListener的实例源码

Netty3JSONResponse.java 文件源码 项目:HeliosStreams 阅读 31 收藏 0 点赞 0 评论 0
/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 */
public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) {
    if(channels!=null && channels.length>0) {
        Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
        if(opCode==null) {
            opCode = "ok";
        }
        TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer());
        for(Channel channel: channels) {
            if(channel!=null && channel.isWritable()) {
                ChannelFuture cf = Channels.future(channel);
                if(listener!=null) cf.addListener(listener);
                channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress()));
                futures.add(cf);
            }
        }
        return futures.toArray(new ChannelFuture[futures.size()]);
    }       
    return EMPTY_CHANNEL_FUTURE_ARR;
}
PathAwayProtocolDecoder.java 文件源码 项目:traccar-service 阅读 29 收藏 0 点赞 0 评论 0
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession = getDeviceSession(
            channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

    position.setValid(true);
    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));

    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
}
TestDelegationTokenRemoteFetcher.java 文件源码 项目:hadoop 阅读 31 收藏 0 点赞 0 评论 0
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
ServerUtil.java 文件源码 项目:bigstreams 阅读 29 收藏 0 点赞 0 评论 0
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
    super.messageReceived(ctx, e);

    System.out.println("-------- Server  Channel messageRecieved "
            + System.currentTimeMillis());

    if (induceError.get()) {
        System.out
                .println("Inducing Error in Server messageReceived method");
        throw new IOException("Induced error ");
    }

    MessageEventBag bag = new MessageEventBag();
    bag.setBytes(e);
    bagList.add(bag);

    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeInt(200);

    ChannelFuture future = e.getChannel().write(buffer);

    future.addListener(ChannelFutureListener.CLOSE);

}
ServerUtil.java 文件源码 项目:bigstreams 阅读 29 收藏 0 点赞 0 评论 0
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
        throws Exception {
    System.out.println("Server Exception Caught");
    e.getCause().printStackTrace();

    /**
     * Very important to respond here.
     * The agent will always be listening for some kind of feedback.
     */
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeInt(500);

    ChannelFuture future = e.getChannel().write(buffer);

    future.addListener(ChannelFutureListener.CLOSE);

}
TestDelegationTokenRemoteFetcher.java 文件源码 项目:big-c 阅读 34 收藏 0 点赞 0 评论 0
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
HttpNullableResponseHandler.java 文件源码 项目:netty-http-3.x 阅读 22 收藏 0 点赞 0 评论 0
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent messageEvent) throws Exception {
    context.getChannel().getPipeline().remove(this);
    Response response = (Response) context.getChannel().getAttachment();

    if (response == null) {
        logger.debug("response is null");
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        httpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, "0");
        httpResponse.setContent(ChannelBuffers.EMPTY_BUFFER);
        httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        context.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);

        return;
    }

    handleHttpResponse(context, response);
}
Netty3JSONResponse.java 文件源码 项目:HeliosStreams 阅读 35 收藏 0 点赞 0 评论 0
/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 */
public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) {
    if(channels!=null && channels.length>0) {
        Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
        if(opCode==null) {
            opCode = "ok";
        }
        TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer());
        for(Channel channel: channels) {
            if(channel!=null && channel.isWritable()) {
                ChannelFuture cf = Channels.future(channel);
                if(listener!=null) cf.addListener(listener);
                channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress()));
                futures.add(cf);
            }
        }
        return futures.toArray(new ChannelFuture[futures.size()]);
    }       
    return EMPTY_CHANNEL_FUTURE_ARR;
}
NettyHelper.java 文件源码 项目:Camel 阅读 40 收藏 0 点赞 0 评论 0
/**
 * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written.
 *
 * @param log             logger to use
 * @param channel         the Netty channel
 * @param remoteAddress   the remote address when using UDP
 * @param body            the body to write (send)
 * @param exchange        the exchange
 * @param listener        listener with work to be executed when the operation is complete
 */
public static void writeBodyAsync(Logger log, Channel channel, SocketAddress remoteAddress, Object body,
                                  Exchange exchange, ChannelFutureListener listener) {
    ChannelFuture future;
    if (remoteAddress != null) {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} remote address: {} writing body: {}", new Object[]{channel, remoteAddress, body});
        }
        future = channel.write(body, remoteAddress);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} writing body: {}", new Object[]{channel, body});
        }
        future = channel.write(body);
    }

    if (listener != null) {
        future.addListener(listener);
    }
}
TestDelegationTokenRemoteFetcher.java 文件源码 项目:hadoop-2.6.0-cdh5.4.3 阅读 30 收藏 0 点赞 0 评论 0
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
NettyClient.java 文件源码 项目:jstorm-0.9.6.3- 阅读 39 收藏 0 点赞 0 评论 0
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
    synchronized (this) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return ;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to closed");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future)
                throws Exception {

            synchronized (this) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
ArmorMessageChannelHandler.java 文件源码 项目:armor 阅读 27 收藏 0 点赞 0 评论 0
@Override
public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) {
    //prevent javax.net.ssl.SSLException: Received close_notify during handshake
    final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);

    if (sslHandler == null) {
        return;
    }

    final ChannelFuture handshakeFuture = sslHandler.handshake();
    handshakeFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (logger.isTraceEnabled()) {
                logger.trace("Node to Node encryption cipher is {}/{}", sslHandler.getEngine().getSession().getProtocol(), sslHandler
                        .getEngine().getSession().getCipherSuite());
            }
            ctx.sendUpstream(e);
        }
    });
}
NettyClient.java 文件源码 项目:learn_jstorm 阅读 26 收藏 0 点赞 0 评论 0
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
    synchronized (this) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return ;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to closed");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future)
                throws Exception {

            synchronized (this) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
FlashPolicyHandler.java 文件源码 项目:works 阅读 51 收藏 0 点赞 0 评论 0
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {

    if (buffer.readableBytes() < 2) {
        return null;
    }

    final int magic1 = buffer.getUnsignedByte(buffer.readerIndex());
    final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1);
    boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p');

    if (isFlashPolicyRequest) {
        l.info("flash policy requested");
        buffer.skipBytes(buffer.readableBytes()); // Discard everything
        channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE);
        return null;
    }

    // Remove ourselves, important since the byte length check at top can hinder frame decoding
    // down the pipeline
    ctx.getPipeline().remove(this);
    return buffer.readBytes(buffer.readableBytes());
}
TestDelegationTokenRemoteFetcher.java 文件源码 项目:FlexMap 阅读 31 收藏 0 点赞 0 评论 0
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
GraphiteSender.java 文件源码 项目:cellhealth-ng 阅读 24 收藏 0 点赞 0 评论 0
public void shutdown() {
    L4j.getL4j().info(SHUTDOWN);
    try {
        this.isShuttingDown = true;
        Channel channel = this.pipeline.getCurrentPipeline().getChannel();
        this.channelFuture.getChannel().write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        L4j.getL4j().info(CLOSE_CHANNEL);
        channelFactory.releaseExternalResources();
        L4j.getL4j().info(RELEASE_FACTORY);
        clientBootstrap.releaseExternalResources();
        L4j.getL4j().info(RELEASE_CLIENT);

    } catch (Exception e) {
        L4j.getL4j().error(new StringBuilder(ERROR_CHANNEL).append(e.toString()).toString(), e);
    }

}
NettyClient.java 文件源码 项目:jstrom 阅读 40 收藏 0 点赞 0 评论 0
/**
 * Avoid channel double close
 *
 * @param channel
 */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to closed");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {

            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
NettyClient.java 文件源码 项目:Tstream 阅读 32 收藏 0 点赞 0 评论 0
/**
 * Avoid channel double close
 * 
 * @param channel
 */
void closeChannel(final Channel channel) {
    synchronized (this) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " is already closed");
            return ;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to closed");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future)
                throws Exception {

            synchronized (this) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " finish closed");
        }
    });
}
PinpointSocketHandler.java 文件源码 项目:apm-agent 阅读 27 收藏 0 点赞 0 评论 0
private void sendClosedPacket(Channel channel) {
    if (!channel.isConnected()) {
        logger.debug("channel already closed. skip sendClosedPacket() {}", channel);
        return;
    }

    logger.debug("write ClientClosePacket");
    ClientClosePacket clientClosePacket = new ClientClosePacket();
    ChannelFuture write = channel.write(clientClosePacket);
    write.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                logger.warn("ClientClosePacket write failed. channel:{}", future.getCause(), future.getCause());
            } else {
                logger.debug("ClientClosePacket write success. channel:{}", future.getChannel());
            }
        }
    });
    write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
}
SocketChannel.java 文件源码 项目:apm-agent 阅读 29 收藏 0 点赞 0 评论 0
public SocketChannel(final Channel channel, long timeoutMillis, Timer timer) {
    if (channel == null) {
        throw new NullPointerException("channel");
    }
    if (timer == null) {
        throw new NullPointerException("channel");
    }
    this.channel = channel;
    this.timeoutMillis = timeoutMillis;
    this.timer = timer;
    this.requestManager = new RequestManager(this.timer);
    this.responseWriteFail = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                logger.warn("responseWriteFail. {}", channel);
            }
        }
    };
}
PinpointServerSocket.java 文件源码 项目:apm-agent 阅读 31 收藏 0 点赞 0 评论 0
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    final Channel channel = e.getChannel();
    logger.info("channelConnected channel:{}", channel);

    if (released) {
        logger.warn("already released. channel:{}", channel);
        channel.write(new ServerClosePacket()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                future.getChannel().close();
            }
        });
        return;
    }
    prepareChannel(channel);

    ChannelContext channelContext = getChannelContext(channel);
    boolean isIgnore = isIgnoreAddress(channel);
    if (!isIgnore) {
        channelContext.changeStateToRunWithoutHandshake();
    }

    super.channelConnected(ctx, e);
}
PinpointServerSocket.java 文件源码 项目:apm-agent 阅读 32 收藏 0 点赞 0 评论 0
private void sendServerClosedPacket() {
    logger.info("sendServerClosedPacket start");
    final ChannelGroupFuture write = this.channelGroup.write(new ServerClosePacket());
    write.awaitUninterruptibly(5000, TimeUnit.MILLISECONDS);
    if (logger.isWarnEnabled()) {
        write.addListener(new ChannelGroupFutureListener() {
            private final ChannelFutureListener listener = new WriteFailFutureListener(logger, "serverClosePacket write fail", "serverClosePacket write success");

            @Override
            public void operationComplete(ChannelGroupFuture future) throws Exception {
                for (ChannelFuture channelFuture : future) {
                    channelFuture.addListener(listener);
                }
            }
        });
    }
    logger.info("sendServerClosedPacket end");
}
NiftyClient.java 文件源码 项目:mandrel 阅读 28 收藏 0 点赞 0 评论 0
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(NiftyClientConnector<T> clientChannelConnector, @Nullable Duration connectTimeout,
        @Nullable Duration receiveTimeout, @Nullable Duration readTimeout, @Nullable Duration sendTimeout, int maxFrameSize,
        @Nullable HostAndPort socksProxyAddress) {
    checkNotNull(clientChannelConnector, "clientChannelConnector is null");

    ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
    bootstrap.setOptions(nettyClientConfig.getBootstrapOptions());

    if (connectTimeout != null) {
        bootstrap.setOption("connectTimeoutMillis", connectTimeout.toMillis());
    }

    bootstrap.setPipelineFactory(clientChannelConnector.newChannelPipelineFactory(maxFrameSize, nettyClientConfig));
    ChannelFuture nettyChannelFuture = clientChannelConnector.connect(bootstrap);
    nettyChannelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            Channel channel = future.getChannel();
            if (channel != null && channel.isOpen()) {
                allChannels.add(channel);
            }
        }
    });
    return new TNiftyFuture<>(clientChannelConnector, receiveTimeout, readTimeout, sendTimeout, nettyChannelFuture);
}
NiftyClient.java 文件源码 项目:mandrel 阅读 35 收藏 0 点赞 0 评论 0
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector, @Nullable final Duration receiveTimeout,
        @Nullable final Duration readTimeout, @Nullable final Duration sendTimeout, final ChannelFuture channelFuture) {
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    Channel nettyChannel = future.getChannel();
                    T channel = clientChannelConnector.newThriftClientChannel(nettyChannel, nettyClientConfig);
                    channel.setReceiveTimeout(receiveTimeout);
                    channel.setReadTimeout(readTimeout);
                    channel.setSendTimeout(sendTimeout);
                    set(channel);
                } else if (future.isCancelled()) {
                    if (!cancel(true)) {
                        setException(new TTransportException("Unable to cancel client channel connection"));
                    }
                } else {
                    throw future.getCause();
                }
            } catch (Throwable t) {
                setException(new TTransportException("Failed to connect client channel", t));
            }
        }
    });
}
WebServerSocketHandler.java 文件源码 项目:trap 阅读 24 收藏 0 点赞 0 评论 0
private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res)
{
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().getCode() != 200)
    {
        res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        setContentLength(res, res.getContent().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || (res.getStatus().getCode() != 200))
    {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
TrackerService.java 文件源码 项目:incubator-twill 阅读 49 收藏 0 点赞 0 评论 0
private void writeResponse(MessageEvent e) {
  HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");

  ChannelBuffer content = ChannelBuffers.dynamicBuffer();
  Writer writer = new OutputStreamWriter(new ChannelBufferOutputStream(content), CharsetUtil.UTF_8);
  reportAdapter.toJson(report.get(), writer);
  try {
    writer.close();
  } catch (IOException e1) {
    LOG.error("error writing resource report", e1);
  }
  response.setContent(content);
  ChannelFuture future = e.getChannel().write(response);
  future.addListener(ChannelFutureListener.CLOSE);
}
FlashPolicyHandler.java 文件源码 项目:restcommander 阅读 36 收藏 0 点赞 0 评论 0
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    if (buffer.readableBytes() < 2) {
        return null;
    }

    final int magic1 = buffer.getUnsignedByte(buffer.readerIndex());
    final int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1);
    boolean isFlashPolicyRequest = (magic1 == '<' && magic2 == 'p');

    if (isFlashPolicyRequest) {
        buffer.skipBytes(buffer.readableBytes()); // Discard everything
        channel.write(policyResponse).addListener(ChannelFutureListener.CLOSE);
        return null;
    }

    // Remove ourselves, important since the byte length check at top can hinder frame decoding
    // down the pipeline
    ctx.getPipeline().remove(this);
    return buffer.readBytes(buffer.readableBytes());
}
ProxyHandler.java 文件源码 项目:flazr 阅读 32 收藏 0 点赞 0 评论 0
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {        
    final Channel inboundChannel = e.getChannel();
    RtmpProxy.ALL_CHANNELS.add(inboundChannel);
    inboundChannel.setReadable(false);        
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handshaker", new ProxyHandshakeHandler());
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
    outboundChannel = f.getChannel();
    f.addListener(new ChannelFutureListener() {
        @Override public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                logger.info("connected to remote host: {}, port: {}", remoteHost, remotePort);
                inboundChannel.setReadable(true);
            } else {                    
                inboundChannel.close();
            }
        }
    });
}
TestDelegationTokenRemoteFetcher.java 文件源码 项目:hadoop-on-lustre2 阅读 28 收藏 0 点赞 0 评论 0
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
NioClientSocketPipelineSink.java 文件源码 项目:android-netty 阅读 35 收藏 0 点赞 0 评论 0
private void connect(
        final NioClientSocketChannel channel, final ChannelFuture cf,
        SocketAddress remoteAddress) {
    try {
        if (channel.channel.connect(remoteAddress)) {
            channel.worker.register(channel, cf);
        } else {
            channel.getCloseFuture().addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture f)
                        throws Exception {
                    if (!cf.isDone()) {
                        cf.setFailure(new ClosedChannelException());
                    }
                }
            });
            cf.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            channel.connectFuture = cf;
            nextBoss().register(channel, cf);
        }

    } catch (Throwable t) {
        cf.setFailure(t);
        fireExceptionCaught(channel, t);
        channel.worker.close(channel, succeededFuture(channel));
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号