Beispiel #1
0
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                  }
                  p.addLast(new DiscardClientHandler());
                }
              });

      // Make the connection attempt.
      ChannelFuture f = b.connect(HOST, PORT).sync();

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      SelfSignedCertificate ssc = new SelfSignedCertificate();
      sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
      sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(new FactorialServerInitializer(sslCtx));

      b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
  public void start(ServerTransportListener listener) {
    Preconditions.checkState(this.listener == null, "Handler already registered");
    this.listener = listener;

    // Create the Netty handler for the pipeline.
    final NettyServerHandler grpcHandler = createHandler(listener);

    // Notify when the channel closes.
    channel
        .closeFuture()
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                notifyTerminated(grpcHandler.connectionError());
              }
            });

    ChannelHandler handler = grpcHandler;
    if (sslContext != null) {
      SSLEngine sslEngine = sslContext.newEngine(channel.alloc());
      handler = ProtocolNegotiators.serverTls(sslEngine, grpcHandler);
    }
    channel.pipeline().addLast(handler);
  }
  public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception {
    URI uri = new URI(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
      if ("http".equalsIgnoreCase(scheme)) {
        port = 80;
      } else if ("https".equalsIgnoreCase(scheme)) {
        port = 443;
      }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new HttpDownloadertInitializer(sslCtx, handler));
      // Make the connection attempt.
      Channel ch = b.connect(host, port).sync().channel();
      // Prepare the HTTP request.
      HttpRequest request =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
      HttpHeaders headers = request.headers();
      headers.set(HttpHeaders.Names.HOST, host);
      headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
      // Set some example cookies.
      headers.set(
          HttpHeaders.Names.COOKIE,
          ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
      ch.writeAndFlush(request);
      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      Thread.sleep(1000);
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
 @Override
 public void initChannel(SocketChannel ch) {
   ChannelPipeline p = ch.pipeline();
   if (sslCtx != null) {
     p.addLast(sslCtx.newHandler(ch.alloc()));
   }
   p.addLast(new HttpClientCodec());
   p.addLast(new HttpContentDecompressor());
   p.addLast(handler);
 }
 @Override
 public void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   if (sslCtx != null) {
     pipeline.addLast(sslCtx.newHandler(ch.alloc()));
   }
   pipeline.addLast(new HttpServerCodec());
   pipeline.addLast(new HttpObjectAggregator(65536));
   pipeline.addLast(new WebSocketServerHandler());
 }
Beispiel #7
0
  private SslContext getSslContext() {
    SslContext sslCtx;
    if (useSsl) {
      SelfSignedCertificate ssc;
      try {
        ssc = new SelfSignedCertificate(host);
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
      } catch (CertificateException | SSLException e) {
        e.printStackTrace();
        sslCtx = null;
      }

    } else {
      sslCtx = null;
    }
    return sslCtx;
  }
  @Override
  public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslCtx != null) {
      pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
    }

    pipeline.addLast("codec", new HttpClientCodec());

    // Remove the following line if you don't want automatic content decompression.
    pipeline.addLast("inflater", new HttpContentDecompressor());

    // to be used since huge file transfer
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

    pipeline.addLast("handler", new HttpUploadClientHandler());
  }
Beispiel #9
0
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      SelfSignedCertificate ssc = new SelfSignedCertificate();
      sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
      sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                  }
                  // p.addLast(new LoggingHandler(LogLevel.INFO));
                  p.addLast(new EchoServerHandler());
                }
              });

      // Start the server.
      ChannelFuture f = b.bind(PORT).sync();

      // Wait until the server socket is closed.
      f.channel().closeFuture().sync();
    } finally {
      // Shut down all event loops to terminate all threads.
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new SecureChatClientInitializer(sslCtx));

      // Start the connection attempt.
      Channel ch = b.connect(HOST, PORT).sync().channel();

      // Read commands from the stdin.
      ChannelFuture lastWriteFuture = null;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      for (; ; ) {
        String line = in.readLine();
        if (line == null) {
          break;
        }

        // Sends the received line to the server.
        lastWriteFuture = ch.writeAndFlush(line + "\r\n");

        // If user typed the 'bye' command, wait until the server closes
        // the connection.
        if ("bye".equals(line.toLowerCase())) {
          ch.closeFuture().sync();
          break;
        }
      }

      // Wait until all messages are flushed before closing the channel.
      if (lastWriteFuture != null) {
        lastWriteFuture.sync();
      }
    } finally {
      // The connection is closed automatically on shutdown.
      group.shutdownGracefully();
    }
  }
  @Override
  public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
  }
 @Override
 protected void initChannel(SocketChannel arg0) {
   CorsConfig corsConfig =
       CorsConfig.withAnyOrigin()
           .allowedRequestHeaders("X-Requested-With", "Content-Type", "Content-Length")
           .allowedRequestMethods(
               HttpMethod.GET,
               HttpMethod.POST,
               HttpMethod.PUT,
               HttpMethod.DELETE,
               HttpMethod.OPTIONS)
           .build();
   ChannelPipeline p = arg0.pipeline();
   if (sslCtx != null) {
     p.addLast(sslCtx.newHandler(arg0.alloc()));
   }
   p.addLast("decoder", new HttpRequestDecoder());
   p.addLast("encoder", new HttpResponseEncoder());
   p.addLast(new CorsHandler(corsConfig));
   p.addLast(new EduMsgNettyServerHandler());
 }
  public static void main(String[] args) throws SSLException, InterruptedException {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
      sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    } else {
      sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .option(ChannelOption.TCP_NODELAY, true)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(@NotNull SocketChannel ch) {
                  ChannelPipeline p = ch.pipeline();
                  if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                  }
                  // p.addLast(new LoggingHandler(LogLevel.INFO));
                  p.addLast(new MyChannelInboundHandler());
                }
              });

      // Start the client.
      ChannelFuture f = b.connect(HOST, PORT).sync();

      // Wait until the connection is closed.
      f.channel().closeFuture().sync();
    } finally {
      // Shut down the event loop to terminate all threads.
      group.shutdownGracefully();
    }
  }
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      SelfSignedCertificate ssc = new SelfSignedCertificate();
      sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
      sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                  }
                  p.addLast(
                      new ObjectEncoder(),
                      new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                      new ObjectEchoServerHandler());
                }
              });

      // Bind and start to accept incoming connections.
      b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
    @Override
    protected void initChannel(Channel channel) throws Exception {
      SslContext sslContext;

      SSLParameters sslParams = new SSLParameters();

      if (redisURI.isVerifyPeer()) {
        sslContext = SslContext.newClientContext(SslProvider.JDK);
        if (JavaRuntime.AT_LEAST_JDK_7) {
          sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        }
      } else {
        sslContext =
            SslContext.newClientContext(SslProvider.JDK, InsecureTrustManagerFactory.INSTANCE);
      }

      SSLEngine sslEngine =
          sslContext.newEngine(channel.alloc(), redisURI.getHost(), redisURI.getPort());
      sslEngine.setSSLParameters(sslParams);

      removeIfExists(channel.pipeline(), SslHandler.class);

      if (channel.pipeline().get("first") == null) {
        channel
            .pipeline()
            .addFirst(
                "first",
                new ChannelDuplexHandler() {

                  @Override
                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    eventBus.publish(new ConnectedEvent(local(ctx), remote(ctx)));
                    super.channelActive(ctx);
                  }

                  @Override
                  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    eventBus.publish(new DisconnectedEvent(local(ctx), remote(ctx)));
                    super.channelInactive(ctx);
                  }
                });
      }

      SslHandler sslHandler = new SslHandler(sslEngine, redisURI.isStartTls());
      channel.pipeline().addLast(sslHandler);
      if (channel.pipeline().get("channelActivator") == null) {
        channel
            .pipeline()
            .addLast(
                "channelActivator",
                new RedisChannelInitializerImpl() {

                  private Command<?, ?, ?> pingCommand;

                  @Override
                  public Future<Boolean> channelInitialized() {
                    return initializedFuture;
                  }

                  @Override
                  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    initializedFuture = SettableFuture.create();
                    pingCommand = null;
                    super.channelInactive(ctx);
                  }

                  @Override
                  public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    if (initializedFuture.isDone()) {
                      super.channelActive(ctx);
                    }
                  }

                  @Override
                  public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
                      throws Exception {
                    if (evt instanceof SslHandshakeCompletionEvent && !initializedFuture.isDone()) {

                      SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
                      if (event.isSuccess()) {
                        if (pingBeforeActivate) {
                          pingCommand = INITIALIZING_CMD_BUILDER.ping();
                          pingBeforeActivate(pingCommand, initializedFuture, ctx, handlers);
                        } else {
                          ctx.fireChannelActive();
                        }
                      } else {
                        initializedFuture.setException(event.cause());
                      }
                    }

                    if (evt instanceof ConnectionEvents.Close) {
                      if (ctx.channel().isOpen()) {
                        ctx.channel().close();
                      }
                    }

                    if (evt instanceof ConnectionEvents.Activated) {
                      if (!initializedFuture.isDone()) {
                        initializedFuture.set(true);
                        eventBus.publish(new ConnectionActivatedEvent(local(ctx), remote(ctx)));
                      }
                    }

                    super.userEventTriggered(ctx, evt);
                  }

                  @Override
                  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                      throws Exception {

                    if (!initializedFuture.isDone()) {
                      initializedFuture.setException(cause);
                    }
                    super.exceptionCaught(ctx, cause);
                  }
                });
      }

      for (ChannelHandler handler : handlers) {
        removeIfExists(channel.pipeline(), handler.getClass());
        channel.pipeline().addLast(handler);
      }
    }