Package io.netty.channel

Examples of io.netty.channel.ChannelFuture


        public void operationComplete(final Future<Channel> future) {
          if (future.isSuccess()) {
            final List<ExpiredToken> expiredTokens = feedbackServer.getAndClearAllExpiredTokens();

            ChannelFuture lastWriteFuture = null;

            for (final ExpiredToken expiredToken : expiredTokens) {
              lastWriteFuture = context.write(expiredToken);
            }

            if (feedbackServer.closeWhenDone) {
              if (lastWriteFuture != null) {
                lastWriteFuture.addListener(ChannelFutureListener.CLOSE);
              } else {
                context.close();
              }
            }
View Full Code Here


     * @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});
            }
            // Need to create AddressedEnvelope to setup the address information here
            DefaultAddressedEnvelope<Object, InetSocketAddress> ae =
                new DefaultAddressedEnvelope<Object, InetSocketAddress>(body, (InetSocketAddress)remoteAddress);
            future = channel.writeAndFlush(ae);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Channel: {} writing body: {}", new Object[]{channel, body});
            }
            // In netty4 we need to call channel flush to send out the message
            future = channel.writeAndFlush(body);
        }

        if (listener != null) {
            future.addListener(listener);
        }
    }
View Full Code Here

     */
    private final class NettyProducerPoolableObjectFactory implements PoolableObjectFactory<Channel> {

        @Override
        public Channel makeObject() throws Exception {
            ChannelFuture channelFuture = openConnection();
            Channel answer = openChannel(channelFuture);
            LOG.trace("Created channel: {}", answer);
            return answer;
        }
View Full Code Here

        return wg;

    }

    protected ChannelFuture openConnection() throws Exception {
        ChannelFuture answer;

        if (isTcp()) {
            // its okay to create a new bootstrap for each new channel
            Bootstrap clientBootstrap = new Bootstrap();
            clientBootstrap.channel(NioSocketChannel.class);
            clientBootstrap.group(getWorkerGroup());
            clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
            clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
            clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
            clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

            //TODO need to check it later
            // set any additional netty options
            /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    clientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/

            // set the pipeline factory, which creates the pipeline for each newly created channels
            clientBootstrap.handler(pipelineFactory);
            answer = clientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                        new Object[]{configuration.getHost(), configuration.getPort(), clientBootstrap});
            }
            return answer;
        } else {
            // its okay to create a new bootstrap for each new channel
            Bootstrap connectionlessClientBootstrap = new Bootstrap();
            connectionlessClientBootstrap.channel(NioDatagramChannel.class);
            connectionlessClientBootstrap.group(getWorkerGroup());
            connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
            connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
            connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
            connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

            //TODO need to check it later
            // set any additional netty options
            /*
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }*/

            // set the pipeline factory, which creates the pipeline for each newly created channels
            connectionlessClientBootstrap.handler(pipelineFactory);
            // bind and store channel so we can close it when stopping
            answer = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
            answer.awaitUninterruptibly();
            Channel channel = answer.channel();
            allChannels.add(channel);
            // if udp connectionless sending is true we don't do a connect.
            // we just send on the channel created with bind which means
            // really fire and forget. You wont get an PortUnreachableException
            // if no one is listen on the port
View Full Code Here

         }
      }

      HornetQClientLogger.LOGGER.debug("Remote destination: " + remoteDestination);

      ChannelFuture future;
      //port 0 does not work so only use local address if set
      if (localPort != 0)
      {
         SocketAddress localDestination;
         if (localAddress != null)
         {
            localDestination = new InetSocketAddress(localAddress, localPort);
         }
         else
         {
            localDestination = new InetSocketAddress(localPort);
         }
         future = bootstrap.connect(remoteDestination, localDestination);
      }
      else
      {
         future = bootstrap.connect(remoteDestination);
      }

      future.awaitUninterruptibly();

      if (future.isSuccess())
      {
         final Channel ch = future.channel();
         SslHandler sslHandler = ch.pipeline().get(SslHandler.class);
         if (sslHandler != null)
         {
            Future<Channel> handshakeFuture = sslHandler.handshakeFuture();
            if (handshakeFuture.awaitUninterruptibly(30000))
            {
               if (handshakeFuture.isSuccess())
               {
                  ChannelPipeline channelPipeline = ch.pipeline();
                  HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
                  channelHandler.active = true;
               }
               else
               {
                  ch.close().awaitUninterruptibly();
                  HornetQClientLogger.LOGGER.errorCreatingNettyConnection(handshakeFuture.cause());
                  return null;
               }
            }
            else
            {
               //handshakeFuture.setFailure(new SSLException("Handshake was not completed in 30 seconds"));
               ch.close().awaitUninterruptibly();
               return null;
            }

         }
         else
         {
            if (httpUpgradeEnabled)
            {
               // Send a HTTP GET + Upgrade request that will be handled by the http-upgrade handler.
               try
               {
                  //get this first incase it removes itself
                  HttpUpgradeHandler httpUpgradeHandler = (HttpUpgradeHandler) ch.pipeline().get("http-upgrade");
                  URI uri = new URI("http", null, host, port, null, null, null);
                  HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
                  request.headers().set(HttpHeaders.Names.HOST, host);
                  request.headers().set(HttpHeaders.Names.UPGRADE, HORNETQ_REMOTING);
                  request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);

                  final String endpoint = ConfigurationHelper.getStringProperty(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME,
                                                                                null,
                                                                                configuration);
                  if (endpoint != null)
                  {
                     request.headers().set(TransportConstants.HTTP_UPGRADE_ENDPOINT_PROP_NAME, endpoint);
                  }

                  // Get 16 bit nonce and base 64 encode it
                  byte[] nonce = randomBytes(16);
                  String key = base64(nonce);
                  request.headers().set(SEC_HORNETQ_REMOTING_KEY, key);
                  ch.attr(REMOTING_KEY).set(key);

                  HornetQClientLogger.LOGGER.debugf("Sending HTTP request %s", request);

                  // Send the HTTP request.
                  ch.writeAndFlush(request);

                  if (!httpUpgradeHandler.awaitHandshake())
                  {
                     return null;
                  }
               }
               catch (URISyntaxException e)
               {
                  HornetQClientLogger.LOGGER.errorCreatingNettyConnection(e);
                  return null;
               }
            }
            else
            {
               ChannelPipeline channelPipeline = ch.pipeline();
               HornetQChannelHandler channelHandler = channelPipeline.get(HornetQChannelHandler.class);
               channelHandler.active = true;
            }
         }

         // No acceptor on a client connection
         Listener connectionListener = new Listener();
         NettyConnection conn = new NettyConnection(configuration, ch, connectionListener, !httpEnabled && batchDelay > 0, false);
         connectionListener.connectionCreated(null, conn, HornetQClient.DEFAULT_CORE_PROTOCOL);
         return conn;
      }
      else
      {
         Throwable t = future.cause();

         if (t != null && !(t instanceof ConnectException))
         {
            HornetQClientLogger.LOGGER.errorCreatingNettyConnection(future.cause());
         }

         return null;
      }
   }
View Full Code Here

            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        } else {
            response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE);
        }

        ChannelFuture future = ctx.write(response);

        if (!isKeepAlive(request)) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
View Full Code Here

        for (int i = 0; i < data.length; i ++) {
            data[i] = (ChannelBuffer) pendingWrites.get(i).getMessage();
        }

        ChannelBuffer composite = ChannelBuffers.wrappedBuffer(data);
        ChannelFuture future = Channels.future(ctx.getChannel());
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future)
                    throws Exception {
                if (future.isSuccess()) {
                    for (MessageEvent e: pendingWrites) {
                        e.getFuture().setSuccess();
                    }
                } else {
                    Throwable cause = future.getCause();
                    for (MessageEvent e: pendingWrites) {
                        e.getFuture().setFailure(cause);
                    }
                }
            }
View Full Code Here

      res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
      setContentLength(res, res.getContent().readableBytes());
    }

    // Send the response and close the connection if necessary.
    final ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
      f.addListener(ChannelFutureListener.CLOSE);
    }
  }
View Full Code Here

    volatile boolean closed;

    @Override
    public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {

        final ChannelFuture future = e.getFuture();

        if (e instanceof ChannelStateEvent) {

            final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
            final ChannelState state = stateEvent.getState();
View Full Code Here

      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);
    }
  }
View Full Code Here

TOP

Related Classes of io.netty.channel.ChannelFuture

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.