@Override
  public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable(false);

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));

    outboundChannel = f.getChannel();
    f.addListener(
        new ChannelFutureListener() {
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              // Connection attempt succeeded:
              // Begin to accept incoming traffic.
              inboundChannel.setReadable(true);
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
  /**
   * Detects if we're connecting to a Found Elasticsearch cluster (using pre-configured host
   * suffixes) and adds a SSL handler at the beginning of the pipeline if we're connecting to a
   * SSL-endpoint (using a list of pre-configured ports).
   */
  @Override
  public void connectRequested(final ChannelHandlerContext ctx, final ChannelStateEvent e)
      throws Exception {
    if (e.getValue() instanceof InetSocketAddress) {
      InetSocketAddress inetSocketAddress = (InetSocketAddress) e.getValue();

      for (String suffix : hostSuffixes) {
        isFoundCluster = isFoundCluster || inetSocketAddress.getHostString().endsWith(suffix);
      }

      if (isFoundCluster) {
        for (int sslPort : sslPorts) {
          if (inetSocketAddress.getPort() == sslPort) {
            logger.debug(
                "Enabling SSL on transport layer with unsafeAllowSelfSigned=[{}].",
                unsafeAllowSelfSigned);
            FoundSSLHandler handler =
                FoundSSLUtils.getSSLHandler(unsafeAllowSelfSigned, inetSocketAddress);
            ctx.getPipeline().addFirst("ssl", handler);
            break;
          }
        }
      } else {
        ctx.getPipeline().remove(this);
      }
    }
    super.connectRequested(ctx, e);
  }
Beispiel #3
0
 public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception {
   if (!(closeNotifyFuture.getCause() instanceof ClosedChannelException)) {
     Channels.close(context, e.getFuture());
   } else {
     e.getFuture().setSuccess();
   }
 }
 @Override
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   AbstractNettyServer.ALL_CHANNELS.add(e.getChannel());
   LOG.debug(
       "Added Channel with id: {} as the {}th open channel",
       e.getChannel().getId(),
       CHANNEL_COUNTER.incrementAndGet());
 }
  /**
   * Attention please,
   *
   * @see
   *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelDisconnected(org.jboss.netty.channel.ChannelHandlerContext,
   *     org.jboss.netty.channel.ChannelStateEvent)
   */
  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    LOG.info(
        "Receive channelDisconnected to {}, channel = {}", client.getRemoteAddr(), e.getChannel());
    // ctx.sendUpstream(e);
    super.channelDisconnected(ctx, e);

    client.disconnectChannel(e.getChannel());
  }
Beispiel #6
0
  public void handleDownstream(final ChannelHandlerContext context, final ChannelEvent evt)
      throws Exception {
    if (evt instanceof ChannelStateEvent) {
      ChannelStateEvent e = (ChannelStateEvent) evt;
      switch (e.getState()) {
        case OPEN:
        case CONNECTED:
        case BOUND:
          if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) {
            closeOutboundAndChannel(context, e);
            return;
          }
      }
    }
    if (!(evt instanceof MessageEvent)) {
      context.sendDownstream(evt);
      return;
    }

    MessageEvent e = (MessageEvent) evt;
    if (!(e.getMessage() instanceof ChannelBuffer)) {
      context.sendDownstream(evt);
      return;
    }

    // Do not encrypt the first write request if this handler is
    // created with startTLS flag turned on.
    if (startTls && sentFirstMessage.compareAndSet(false, true)) {
      context.sendDownstream(evt);
      return;
    }

    // Otherwise, all messages are encrypted.
    ChannelBuffer msg = (ChannelBuffer) e.getMessage();
    PendingWrite pendingWrite;

    if (msg.readable()) {
      pendingWrite =
          new PendingWrite(
              evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes()));
    } else {
      pendingWrite = new PendingWrite(evt.getFuture(), null);
    }
    synchronized (pendingUnencryptedWrites) {
      boolean offered = pendingUnencryptedWrites.offer(pendingWrite);
      assert offered;
    }

    wrap(context, evt.getChannel());
  }
Beispiel #7
0
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {

      final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
      NioWorker worker = ch.getWorker();

      // Choose a handler
      final HandlerHolder handler = handlerManager.chooseHandler(worker);

      if (handler == null) {
        // Ignore
        return;
      }

      VertxInternal.instance.executeOnContext(
          handler.contextID,
          new Runnable() {
            public void run() {
              VertxInternal.instance.setContextID(handler.contextID);
              NetSocket sock = new NetSocket(ch, handler.contextID, Thread.currentThread());
              socketMap.put(ch, sock);
              handler.handler.handle(sock);
            }
          });
    }
Beispiel #8
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = e.getChannel();
   logger.info("channel disconnected at :{}", channel);
   streamClientListener.onDisconnected(channel);
   super.channelDisconnected(ctx, e);
 }
Beispiel #9
0
 @Override
 public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
   final DefaultNetSocket sock = socketMap.get(ch);
   ChannelState state = e.getState();
   if (state == ChannelState.INTEREST_OPS) {
     sock.getContext()
         .execute(
             new Runnable() {
               public void run() {
                 sock.handleInterestedOpsChanged();
               }
             });
   }
 }
Beispiel #10
0
 @Override
 public void channelDisconnected(final ChannelHandlerContext ctx, final ChannelStateEvent e)
     throws Exception {
   chan = null;
   super.channelDisconnected(ctx, e); // Let the ReplayingDecoder cleanup.
   cleanup(e.getChannel());
 }
Beispiel #11
0
  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    // Make sure the handshake future is notified when a connection has
    // been closed during handshake.
    synchronized (handshakeLock) {
      if (handshaking) {
        handshakeFuture.setFailure(new ClosedChannelException());
      }
    }

    try {
      super.channelDisconnected(ctx, e);
    } finally {
      unwrap(ctx, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
      engine.closeOutbound();
      if (!sentCloseNotify.get() && handshaken) {
        try {
          engine.closeInbound();
        } catch (SSLException ex) {
          logger.debug("Failed to clean up SSLEngine.", ex);
        }
      }
    }
  }
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   String welcome =
       "Welcome to Onion Router!\nYou're node name is "
           + GlobalVars.nodeName()
           + "\nType each command with a trailing semicolon\nType 'help;' to see the commands\n\n>";
   TerminalWrite.write(e.getChannel(), welcome);
 }
  /** 向server端发送消息 */
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
    System.out.println("client start..");

    String message = "[" + name + "]baicai AAA";
    ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(message.getBytes());
    event.getChannel().write(channelBuffer);
  }
Beispiel #14
0
 @Override
 public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) {
   chan = null;
   // No need to call super.channelClosed() because we already called
   // super.channelDisconnected().  If we get here without getting a
   // DISCONNECTED event, then we were never connected in the first place so
   // the ReplayingDecoder has nothing to cleanup.
   cleanup(e.getChannel());
 }
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   lock.acquire();
   try {
     channelSetter.setChannel(e.getChannel());
   } finally {
     lock.release();
   }
 }
 @Override
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent channelStateEvent)
     throws Exception {
   if (LOG.isTraceEnabled()) {
     LOG.trace("Channel open: {}", ctx.getChannel());
   }
   // to keep track of open sockets
   producer.getAllChannels().add(channelStateEvent.getChannel());
 }
Beispiel #17
0
  @Override
  public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) {
    final Channel chan = e.getChannel();
    ChannelBuffer header = connectionHeaderPreamble();
    header.writerIndex(RPC_HEADER.length);
    Channels.write(chan, header);

    secureRpcHelper = new SecureRpcHelper(this);
    secureRpcHelper.sendHello(chan);
  }
Beispiel #18
0
  private void closeOutboundAndChannel(
      final ChannelHandlerContext context, final ChannelStateEvent e) throws SSLException {
    if (!e.getChannel().isConnected()) {
      context.sendDownstream(e);
      return;
    }

    unwrap(context, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
    if (!engine.isInboundDone()) {
      if (sentCloseNotify.compareAndSet(false, true)) {
        engine.closeOutbound();
        ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel());
        closeNotifyFuture.addListener(new ClosingChannelFutureListener(context, e));
        return;
      }
    }

    context.sendDownstream(e);
  }
Beispiel #19
0
  @Override
  public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    super.channelClosed(ctx, e);

    if (!ctx.getChannel().isOpen()) {
      tryToFinishOffChannel(ctx.getChannel());
    }

    channelGroup.remove(e.getChannel());
  }
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   Channel channel = e.getChannel();
   System.out.println(channel.getRemoteAddress().toString());
   System.out.println("channelConnected...");
   String msg = "welcome rookiefly...";
   ChannelBuffer buffer = ChannelBuffers.buffer(1024);
   buffer.writeBytes(msg.getBytes());
   channel.write(buffer);
   ctx.sendUpstream(e);
 }
 private void sendNumbers(ChannelStateEvent e) {
   Channel channel = e.getChannel();
   while (channel.isWritable()) {
     if (i <= count) {
       channel.write(Integer.valueOf(i));
       i++;
     } else {
       break;
     }
   }
 }
  /** Sometime when connect one bad channel which isn't writable, it will call this function */
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent event) {
    // register the newly established channel
    Channel channel = event.getChannel();
    LOG.info(
        "connection established to :{}, local port:{}",
        client.getRemoteAddr(),
        channel.getLocalAddress());

    client.handleResponse();
  }
 @Override
 public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   // If inboundChannel is not saturated anymore, continue accepting
   // the incoming traffic from the outboundChannel.
   synchronized (trafficLock) {
     if (e.getChannel().isWritable()) {
       outboundChannel.setReadable(true);
     }
   }
 }
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   // Событие вызывается при подключении клиента. Я создаю здесь Worker игрока — объект, который
   // занимается обработкой данных игрока
   // непостредственно.
   // Я передаю ему канал игрока (функция e.getChannel()), чтобы он мог в него посылать пакеты
   worker = workerClass.newInstance();
   worker.setChannel(e.getChannel());
   worker.setClientHandler(this);
   // worker = new InterserverWorker(this, e.getChannel());
   // log.info("channelConnected");
 }
Beispiel #25
0
 @Override
 public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e)
     throws Exception {
   final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
   final ClientConnection conn = connectionMap.get(ch);
   runOnCorrectThread(
       ch,
       new Runnable() {
         public void run() {
           conn.handleInterestedOpsChanged();
         }
       });
 }
Beispiel #26
0
 @Override
 @LogMessageDoc(
     message = "New switch connection from {ip address}",
     explanation = "A new switch has connected from the " + "specified IP address")
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   log.debug(
       "channelConnected on OFChannelHandler {}",
       String.format("%08x", System.identityHashCode(this)));
   counters.switchConnected.increment();
   channel = e.getChannel();
   log.info("New switch connection from {}", channel.getRemoteAddress());
   setState(new WaitHelloState());
 }
 /**
  * Handle downstream event.
  *
  * @param pipeline the {@link ChannelPipeline} that passes down the downstream event.
  * @param e The downstream event.
  */
 @Override
 public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {
   final NioDatagramChannel channel = (NioDatagramChannel) e.getChannel();
   final ChannelFuture future = e.getFuture();
   if (e instanceof ChannelStateEvent) {
     final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
     final ChannelState state = stateEvent.getState();
     final Object value = stateEvent.getValue();
     switch (state) {
       case OPEN:
         if (Boolean.FALSE.equals(value)) {
           channel.worker.close(channel, future);
         }
         break;
       case BOUND:
         if (value != null) {
           bind(channel, future, (InetSocketAddress) value);
         } else {
           channel.worker.close(channel, future);
         }
         break;
       case CONNECTED:
         if (value != null) {
           connect(channel, future, (InetSocketAddress) value);
         } else {
           NioDatagramWorker.disconnect(channel, future);
         }
         break;
       case INTEREST_OPS:
         channel.worker.setInterestOps(channel, future, ((Integer) value).intValue());
         break;
     }
   } else if (e instanceof MessageEvent) {
     final MessageEvent event = (MessageEvent) e;
     final boolean offered = channel.writeBufferQueue.offer(event);
     assert offered;
     channel.worker.writeFromUserCode(channel);
   }
 }
Beispiel #28
0
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
   final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
   final ClientConnection conn = connectionMap.remove(ch);
   if (conn != null) {
     runOnCorrectThread(
         ch,
         new Runnable() {
           public void run() {
             conn.handleClosed();
           }
         });
   }
 }
Beispiel #29
0
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
   final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
   final NetSocket sock = socketMap.remove(ch);
   if (sock != null) {
     VertxInternal.instance.executeOnContext(
         sock.getContextID(),
         new Runnable() {
           public void run() {
             sock.handleClosed();
           }
         });
   }
 }
Beispiel #30
0
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
   final NioSocketChannel ch = (NioSocketChannel) e.getChannel();
   final DefaultNetSocket sock = socketMap.remove(ch);
   if (sock != null) {
     sock.getContext()
         .execute(
             new Runnable() {
               public void run() {
                 sock.handleClosed();
               }
             });
   }
 }