Exemplo n.º 1
0
 // Synchronous HTTP action
 @Override
 public String httpActionSync(
     String uri,
     String method,
     List<HttpParam> parametersQuery,
     List<HttpParam> parametersForm,
     List<HttpResponse> errors)
     throws RestException {
   Channel ch;
   try {
     HttpRequest request = buildRequest(uri, method, parametersQuery, parametersForm);
     // handler.reset();
     ch = bootStrap.connect(baseUri.getHost(), baseUri.getPort()).sync().channel();
     NettyHttpClientHandler handler = (NettyHttpClientHandler) ch.pipeline().get("http-handler");
     ch.writeAndFlush(request);
     ch.closeFuture().sync();
     if (httpResponseOkay(handler.getResponseStatus())) {
       return handler.getResponseText();
     } else {
       throw makeException(handler.getResponseStatus(), handler.getResponseText(), errors);
     }
   } catch (InterruptedException e) {
     throw new RestException(e);
   }
 }
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
      SelfSignedCertificate ssc = new SelfSignedCertificate();
      sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } 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 WebSocketServerInitializer(sslCtx));

      Channel ch = b.bind(PORT).sync().channel();

      System.out.println(
          "Open your web browser and navigate to "
              + (SSL ? "https" : "http")
              + "://127.0.0.1:"
              + PORT
              + '/');

      ch.closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 3
0
  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioDatagramChannel.class)
          .option(ChannelOption.SO_BROADCAST, true)
          .handler(new QuoteOfTheMomentClientHandler());

      Channel ch = b.bind(0).sync().channel();

      // Broadcast the QOTM request to port 8080.
      ch.write(
              new DatagramPacket(
                  Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                  new InetSocketAddress("255.255.255.255", port)))
          .flush()
          .sync();

      // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
      // response is received.  If the channel is not closed within 5 seconds,
      // print an error message and quit.
      if (!ch.closeFuture().await(5000)) {
        System.err.println("QOTM request timed out.");
      }
    } finally {
      group.shutdownGracefully();
    }
  }
Exemplo n.º 4
0
  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);
  }
Exemplo n.º 5
0
  public void run(URI uri) throws Exception {
    int port = uri.getPort() > 0 ? uri.getPort() : BaseTestConfig.HTTPS_PORT;
    String host = uri.getHost();

    // Configure SSL context if necessary.
    final SslContext sslCtx;
    sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    httpsInitializer = generateHttpsInitializer(sslCtx);
    try {
      Bootstrap b = new Bootstrap();
      b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
      b.group(group).channel(NioSocketChannel.class).handler(httpsInitializer);

      // Make the connection attempt.
      startTime = System.nanoTime();
      Channel ch = b.connect(host, port).sync().channel();
      localAddress = ch.localAddress();
      remoteAddress = ch.remoteAddress();

      sendRequests(uri.toURL(), ch);

      // Wait for the server to close the connection.
      ch.closeFuture().sync();
      endTime = System.nanoTime();
      long duration = endTime - startTime;
      logger.info(String.format("connection duration: %,dns (%d)", duration, duration));
    } finally {
      // Shut down executor threads to exit.
      group.shutdownGracefully();
    }
  }
Exemplo n.º 6
0
  public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {

      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  // 将请求和应答消息编码或者解码为http消息
                  ch.pipeline().addLast("http-codec", new HttpServerCodec());
                  // 目的是将http消息的多个部分组成一条完整的http消息
                  ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                  // 来向客户端发送html5文件,它主要用于支持浏览器和服务端进行WebSocket通信
                  ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                  ch.pipeline().addLast("handler", new WebSocketServerHandler());
                }
              });

      Channel ch = b.bind(port).sync().channel();
      System.out.println("Web socket server started at port" + port + ".");
      System.out.println("Open your browser and navigate to http://127.0.0.1:" + port + "/");
      ch.closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 7
0
  @Override
  public void start() throws Exception {

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap
          .group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .handler(
              new ChannelInitializer<ServerSocketChannel>() {
                @Override
                protected void initChannel(ServerSocketChannel ch) throws Exception {
                  ch.pipeline().addLast("log", new LoggingHandler(LogLevel.INFO));
                  ch.pipeline()
                      .addLast(
                          "redis", Tangerine.getInstance().getBean(NotifyServiceHandler.class));
                }
              })
          .childHandler(new ServerChannelInitializer())
          .option(ChannelOption.SO_BACKLOG, 1024);

      channel = bootstrap.bind(host, port).sync().channel();
      channel.closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 8
0
  public static void newHttpServerBootstrap(
      String ip, int port, ChannelInitializer<SocketChannel> channelInitializer) {
    // Configure the server.
    int numCPUs = Runtime.getRuntime().availableProcessors();
    EventLoopGroup bossGroup = new NioEventLoopGroup(numCPUs);
    EventLoopGroup workerGroup = new NioEventLoopGroup(numCPUs);
    try {
      // public service processor
      ServerBootstrap publicServerBootstrap = new ServerBootstrap();
      publicServerBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
      publicServerBootstrap
          .childOption(ChannelOption.TCP_NODELAY, false)
          .childOption(ChannelOption.SO_KEEPALIVE, false)
          .childHandler(channelInitializer);

      // bind to public access host info
      Channel ch1;
      if ("*".equals(ip)) {
        ch1 = publicServerBootstrap.bind(port).sync().channel();
      } else {
        ch1 = publicServerBootstrap.bind(ip, port).sync().channel();
      }
      System.out.println(String.format("Started OK HttpServer at %s:%d", ip, port));
      ch1.config().setConnectTimeoutMillis(1800);
      ch1.closeFuture().sync();
      System.out.println("Shutdown...");
    } catch (Throwable e) {
      e.printStackTrace();
      System.exit(1);
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println("Starting HystrixMetricsReactiveSocketServer...");

    final ReactiveSocketServerHandler handler =
        ReactiveSocketServerHandler.create((setupPayload, rs) -> new EventStreamRequestHandler());

    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<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                  ChannelPipeline pipeline = ch.pipeline();
                  pipeline.addLast(handler);
                }
              });
      Channel localhost = b.bind("127.0.0.1", 8025).sync().channel();

      executeCommands();
      localhost.closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 10
0
  public void bind(int port) {
    EventLoopGroup bossGrouop = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGrouop, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                  ChannelPipeline pipeline = socketChannel.pipeline();
                  pipeline.addLast(new DispatchHandler());
                  pipeline.addLast("http-codec", new HttpServerCodec());
                  pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                  pipeline.addLast("http-chunked", new ChunkedWriteHandler());
                  pipeline.addLast(new WebSocketServerHandler());
                }
              });

      Channel channel = b.bind(port).sync().channel();
      System.out.println("服务端启动");
      channel.closeFuture().sync();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      bossGrouop.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 11
0
 public void start() throws InterruptedException, URISyntaxException {
   EventLoopGroup group = new NioEventLoopGroup();
   try {
     Bootstrap b = new Bootstrap();
     b.group(group).channel(NioSocketChannel.class);
     b.handler(
         new ChannelInitializer<Channel>() {
           @Override
           protected void initChannel(Channel ch) throws Exception {
             ChannelPipeline pipeline = ch.pipeline();
             pipeline.addLast("decoder", new RtspResponseDecoder());
             pipeline.addLast("encoder", new RtspRequestEncoder());
             pipeline.addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 64));
             pipeline.addLast("handler", new ResponseHandler());
           }
         });
     b.option(ChannelOption.SO_KEEPALIVE, true);
     ChannelFuture channelFutrue = b.connect(host, port).sync();
     if (channelFutrue.isSuccess()) {
       channel = channelFutrue.channel();
       URI uri = new URI("rtsp://127.0.0.1:554/hello-world");
       HttpRequest request = this.buildOptionsRequest(uri.toASCIIString());
       this.send(request);
       channel.closeFuture().sync();
     }
   } finally {
     // 优雅退出,释放NIO线程组
     group.shutdownGracefully();
   }
 }
Exemplo n.º 12
0
  public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap b = new Bootstrap();
      String protocol = uri.getScheme();
      if (!"ws".equals(protocol)) {
        throw new IllegalArgumentException("Unsupported protocol: " + protocol);
      }

      HttpHeaders customHeaders = new DefaultHttpHeaders();
      customHeaders.add("MyHeader", "MyValue");

      // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
      // If you change it to V00, ping is not supported and remember to change
      // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
      final WebSocketClientHandler handler =
          new WebSocketClientHandler(
              WebSocketClientHandshakerFactory.newHandshaker(
                  uri, WebSocketVersion.V13, null, false, customHeaders));

      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline pipeline = ch.pipeline();
                  pipeline.addLast("http-codec", new HttpClientCodec());
                  pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                  pipeline.addLast("ws-handler", handler);
                }
              });

      System.out.println("WebSocket Client connecting");
      Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
      handler.handshakeFuture().sync();

      // Send 10 messages and wait for responses
      System.out.println("WebSocket Client sending message");
      for (int i = 0; i < 10; i++) {
        ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
      }

      // Ping
      System.out.println("WebSocket Client sending ping");
      ch.writeAndFlush(
          new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] {1, 2, 3, 4, 5, 6})));

      // Close
      System.out.println("WebSocket Client sending close");
      ch.writeAndFlush(new CloseWebSocketFrame());

      // WebSocketClientHandler will close the connection when the server
      // responds to the CloseWebSocketFrame.
      ch.closeFuture().sync();
    } finally {
      group.shutdownGracefully();
    }
  }
Exemplo n.º 13
0
    public Channel getActiveChannel() throws InterruptedException {
      List<InetSocketAddress> addresses = m_descriptor.getRemoteAddresses();

      if (!addresses.equals(m_addresses)) { // first time or addresses changed
        m_addresses = addresses;

        for (int i = 0; i < addresses.size(); i++) {
          InetSocketAddress address = addresses.get(i);
          ChannelFuture future = m_bootstrap.connect(address).sync();

          if (future.isSuccess()) {
            // close old channel
            if (m_channel != null) {
              m_channel.close();
            }

            // m_logger.info(String.format("Connected to %s server(%s:%s)", m_descriptor.getName(),
            // address.getHostName(), address.getPort()));
            m_channel = future.channel();
            m_index = i;
            break;
          }
        }

        return m_channel;
      } else {
        // closed by peer
        if (m_channel != null && m_channel.closeFuture().isSuccess()) {
          // TODO
        }

        // try to recover connection to primary server
        if (m_index > 0) {
          if (m_primary == null) {
            long now = System.currentTimeMillis();

            if (m_lastCheckTime + m_failBackCheckInternal < now) {
              InetSocketAddress address = m_addresses.get(m_index);

              m_lastCheckTime = now;
              m_primary = m_bootstrap.connect(address);
            }
          } else {
            Channel channel = m_primary.channel();

            if (channel.isOpen() && channel.isActive()) {
              m_channel = channel;
              m_index = 0;
            }
          }
        }

        if (m_channel != null && m_channel.isOpen() && m_channel.isActive()) {
          return m_channel;
        } else {
          return null;
        }
      }
    }
Exemplo n.º 14
0
 public void stop() {
   channel.close();
   try {
     channel.closeFuture().await();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 15
0
 public void runServer() throws Exception {
   final ServerBootstrap sb = new ServerBootstrap();
   try {
     sb.group(new NioEventLoopGroup(), new NioEventLoopGroup())
         .channel(NioServerSocketChannel.class)
         .childHandler(
             new ChannelInitializer<SocketChannel>() {
               @Override
               public void initChannel(final SocketChannel ch) throws Exception {
                 ch.pipeline()
                     .addLast(
                         new HttpRequestDecoder(),
                         new HttpObjectAggregator(65536),
                         new HttpResponseEncoder(),
                         new WebSocketServerProtocolHandler("/websocket"));
               }
             });
     final Channel ch = sb.bind(8080).sync().channel();
     context
         .getScheduler()
         .scheduleWithFixedDelay(
             new Runnable() {
               @Override
               public void run() {
                 if (ch != null) {
                   if (ch.isActive()) {
                     String report = reporter.makeReport();
                     ch.write(new TextWebSocketFrame(report));
                     ch.flush();
                     log.info("Report sent");
                   } else {
                     log.warn(
                         "Cannot send report on channel (A,O,R) ("
                             + ch.isActive()
                             + ", "
                             + ch.isOpen()
                             + ", "
                             + ch.isRegistered()
                             + ")");
                   }
                 } else {
                   log.error("Channel is null!");
                 }
               }
             },
             15,
             context.getProps().getReportLogInterval(),
             TimeUnit.SECONDS);
     log.info("Web socket server started at port " + 8080);
     ch.closeFuture().sync();
     log.info("Web socket server stoped");
   } finally {
     sb.shutdown();
     log.info("Web socket server shutdown");
   }
 }
Exemplo n.º 16
0
  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();
    }
  }
Exemplo n.º 17
0
  public FileChunk get() throws IOException {
    if (useLocalFile) {
      startTime = System.currentTimeMillis();
      finishTime = System.currentTimeMillis();
      state = TajoProtos.FetcherState.FETCH_FINISHED;
      return fileChunk;
    }

    this.startTime = System.currentTimeMillis();
    this.state = TajoProtos.FetcherState.FETCH_FETCHING;
    ChannelFuture future = null;
    try {
      future =
          bootstrap
              .clone()
              .connect(new InetSocketAddress(host, port))
              .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);

      // Wait until the connection attempt succeeds or fails.
      Channel channel = future.awaitUninterruptibly().channel();
      if (!future.isSuccess()) {
        state = TajoProtos.FetcherState.FETCH_FAILED;
        throw new IOException(future.cause());
      }

      String query = uri.getPath() + (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : "");
      // Prepare the HTTP request.
      HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query);
      request.headers().set(HttpHeaders.Names.HOST, host);
      request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
      request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

      LOG.info("Status: " + getState() + ", URI:" + uri);
      // Send the HTTP request.
      channel.writeAndFlush(request);

      // Wait for the server to close the connection. throw exception if failed
      channel.closeFuture().syncUninterruptibly();

      fileChunk.setLength(fileChunk.getFile().length());
      return fileChunk;
    } finally {
      if (future != null && future.channel().isOpen()) {
        // Close the channel to exit.
        future.channel().close().awaitUninterruptibly();
      }

      this.finishTime = System.currentTimeMillis();
      LOG.info(
          "Fetcher finished:" + (finishTime - startTime) + " ms, " + getState() + ", URI:" + uri);
    }
  }
  public void stop() throws Exception {
    shutdown.set(true);

    try {
      // Wait for channel to be closed
      if (acceptorChannel != null) {
        acceptorChannel.close();
        acceptorChannel.closeFuture().sync();
      }
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 19
0
  @Test
  public void testLocalAddressReuse() throws Exception {

    for (int i = 0; i < 2; i++) {
      LocalAddress addr = new LocalAddress(LOCAL_ADDR_ID);
      Bootstrap cb = new Bootstrap();
      ServerBootstrap sb = new ServerBootstrap();

      cb.eventLoop(new LocalEventLoop())
          .channel(new LocalChannel())
          .remoteAddress(addr)
          .handler(new TestHandler());

      sb.eventLoop(new LocalEventLoop(), new LocalEventLoop())
          .channel(new LocalServerChannel())
          .localAddress(addr)
          .childHandler(
              new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel ch) throws Exception {
                  ch.pipeline().addLast(new TestHandler());
                }
              });

      // Start server
      Channel sc = sb.bind().sync().channel();

      // Connect to the server
      Channel cc = cb.connect().sync().channel();

      // Send a message event up the pipeline.
      cc.pipeline().inboundMessageBuffer().add("Hello, World");
      cc.pipeline().fireInboundBufferUpdated();

      // Close the channel
      cc.close().sync();

      sb.shutdown();
      cb.shutdown();

      sc.closeFuture().sync();

      Assert.assertTrue(
          String.format(
              "Expected null, got channel '%s' for local address '%s'",
              LocalChannelRegistry.get(addr), addr),
          LocalChannelRegistry.get(addr) == null);
    }
  }
Exemplo n.º 20
0
  @Test
  public void listenerExceptionShouldCloseConnection() throws Exception {
    final Http2Headers headers = dummyHeaders();
    doThrow(new RuntimeException("Fake Exception"))
        .when(serverListener)
        .onHeadersRead(
            any(ChannelHandlerContext.class),
            eq(3),
            eq(headers),
            eq(0),
            eq((short) 16),
            eq(false),
            eq(0),
            eq(false));

    bootstrapEnv(1, 0, 1, 1);

    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel
        .closeFuture()
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                closeLatch.countDown();
              }
            });

    // Create a single stream by sending a HEADERS frame to the server.
    runInChannel(
        clientChannel,
        new Http2Runnable() {
          @Override
          public void run() {
            http2Client
                .encoder()
                .writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
          }
        });

    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(5, SECONDS));
    assertTrue(requestLatch.await(5, SECONDS));

    // Wait for the close to occur.
    assertTrue(closeLatch.await(5, SECONDS));
    assertFalse(clientChannel.isOpen());
  }
Exemplo n.º 21
0
  public NetworkServer(NetworkManager manager, int port) {
    this.manager = manager;
    b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new NetworkServerConnectionInitializer(manager));
    try {
      Channel ch = b.bind(port).sync().channel();

      ch.closeFuture().sync();
    } catch (InterruptedException interrupt) {
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 22
0
  @Test
  public void nonHttp2ExceptionInPipelineShouldNotCloseConnection() throws Exception {
    bootstrapEnv(1, 1, 1, 1);

    // Create a latch to track when the close occurs.
    final CountDownLatch closeLatch = new CountDownLatch(1);
    clientChannel
        .closeFuture()
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                closeLatch.countDown();
              }
            });

    // Create a single stream by sending a HEADERS frame to the server.
    final Http2Headers headers = dummyHeaders();
    runInChannel(
        clientChannel,
        new Http2Runnable() {
          @Override
          public void run() {
            http2Client
                .encoder()
                .writeHeaders(ctx(), 3, headers, 0, (short) 16, false, 0, false, newPromise());
          }
        });

    // Wait for the server to create the stream.
    assertTrue(serverSettingsAckLatch.await(5, SECONDS));
    assertTrue(requestLatch.await(5, SECONDS));

    // Add a handler that will immediately throw an exception.
    clientChannel
        .pipeline()
        .addFirst(
            new ChannelHandlerAdapter() {
              @Override
              public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                throw new RuntimeException("Fake Exception");
              }
            });

    // The close should NOT occur.
    assertFalse(closeLatch.await(5, SECONDS));
    assertTrue(clientChannel.isOpen());
  }
  public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx =
        SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap bootstrap =
          new Bootstrap()
              .group(group)
              .channel(NioSocketChannel.class)
              .handler(new SimpleNettyClientInitializer(sslCtx));

      // Start the connection attempt.
      Channel ch = bootstrap.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);

        // 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();
    }
  }
Exemplo n.º 24
0
  public void run() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    try {
      b.group(new NioEventLoopGroup(), new NioEventLoopGroup())
          .channel(NioServerSocketChannel.class)
          .localAddress(port)
          .childHandler(new HttpUploadServerInitializer());

      Channel ch = b.bind().sync().channel();
      System.out.println("HTTP Upload Server at port " + port + '.');
      System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

      ch.closeFuture().sync();
    } finally {
      b.shutdown();
    }
  }
 @Override
 public void send(String msg) {
   if ("bye".equals(msg.toLowerCase())) {
     channel.writeAndFlush(new CloseWebSocketFrame());
     try {
       channel.closeFuture().sync();
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   } else if ("ping".equals(msg.toLowerCase())) {
     WebSocketFrame frame =
         new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[] {8, 1, 8, 1}));
     channel.writeAndFlush(frame);
   } else {
     WebSocketFrame frame = new TextWebSocketFrame(msg);
     channel.writeAndFlush(frame);
   }
 }
Exemplo n.º 26
0
  public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.option(ChannelOption.SO_BACKLOG, 1024);
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new SpdyServerInitializer());

      Channel ch = b.bind(port).sync().channel();
      ch.closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Exemplo n.º 27
0
  protected ChannelFutureListener connectionListener(
      ConnectCallback connectCallback,
      CatchingConsumer success,
      ChannelFutureListener closeHandler) {

    return (channelFuture) -> {
      if (channelFuture.isSuccess()) {
        Channel channel = channelFuture.channel();
        channel.closeFuture().addListener(closeHandler);
        success.consume(channel);
      } else {
        Throwable cause = channelFuture.cause();
        if (cause != null) {
          connectCallback.on(cause);
        } else {
          connectCallback.on(null, null);
        }
      }
    };
  }
 public void run() throws Exception {
   final DataStore datastore = new InMemoryDataStore();
   final EventLoopGroup bossGroup = new NioEventLoopGroup();
   final EventLoopGroup workerGroup = new NioEventLoopGroup();
   final DefaultEventExecutorGroup reaperExcutorGroup = new DefaultEventExecutorGroup(1);
   try {
     final ServerBootstrap sb = new ServerBootstrap();
     sb.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(
             new SockJSChannelInitializer(
                 simplePushConfig, datastore, sockJSConfig, reaperExcutorGroup));
     final Channel ch = sb.bind(simplePushConfig.host(), simplePushConfig.port()).sync().channel();
     System.out.println("SockJS server with options " + options);
     ch.closeFuture().sync();
   } finally {
     bossGroup.shutdownGracefully();
     workerGroup.shutdownGracefully();
   }
 }
Exemplo n.º 29
0
  public static void main(final String... args) throws InterruptedException {
    final ProgressMeter meter = new ProgressMeter("requests");

    // Codecs

    // Server
    final ServerBootstrap serverBootstrap =
        new ServerBootstrap()
            .group(new NioEventLoopGroup(1), new NioEventLoopGroup())
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(
                new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(ZMTPCodec.builder().socketType(ROUTER).build());
                    ch.pipeline().addLast(new ServerHandler());
                  }
                });
    final Channel server = serverBootstrap.bind(ANY_PORT).awaitUninterruptibly().channel();

    // Client
    final SocketAddress address = server.localAddress();
    final Bootstrap clientBootstrap =
        new Bootstrap()
            .group(new NioEventLoopGroup())
            .channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .handler(
                new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(ZMTPCodec.builder().socketType(DEALER).build());
                    ch.pipeline().addLast(new ClientHandler(meter));
                  }
                });
    final Channel client = clientBootstrap.connect(address).awaitUninterruptibly().channel();

    // Run until client is closed
    client.closeFuture().await();
  }
Exemplo n.º 30
0
  public void run() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.option(ChannelOption.SO_BACKLOG, 1024);
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(initializer);

      channel = b.bind(address).sync().channel();

      channel.closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }