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();
    }
  }
Esempio n. 2
0
  /*
   * bean的初始化
   */
  public void afterPropertiesSet() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap
          .group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .option(ChannelOption.SO_REUSEADDR, true)
          .childOption(ChannelOption.SO_KEEPALIVE, true)
          .childHandler(
              new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline()
                      .addLast(new Encoder(Response.class))
                      .addLast(new Decoder(Request.class))
                      .addLast(new IdleStateHandler(0, 0, IDLE_TIME))
                      .addLast(new ServerHeartBeatHandler())
                      .addLast(new ServerHandler(exportClassMap));
                }
              });

      ChannelFuture future = bootstrap.bind(addressProvider.getPort()).sync();
      System.out.println("start server...");

      future.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 3
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;
    }

    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();
    }
  }
Esempio n. 4
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();
    }
  }
Esempio n. 5
0
  public static void main(String args[]) throws Exception {
    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)
          // .childOption(ChannelOption.SO_KEEPALIVE, true)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline p = ch.pipeline();
                  p.addLast(new IdleStateHandler(20, 10, 0));
                  p.addLast(new NettyServerHandler());
                }
              });

      ChannelFuture f = b.bind(8080).sync();

      f.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 6
0
  public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // Configure the server.
    ServerBootstrap bootstrap;
    try {
      bootstrap = new ServerBootstrap();
      bootstrap
          .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 {
                  ch.pipeline().addLast(new ServerHandler());
                }
              });
      // Start the server.
      ChannelFuture f = bootstrap.bind(8080).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();
    }
  }
Esempio n. 7
0
  public void run() throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup();

    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap b = new ServerBootstrap(); // (2)
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class) // (3)
          .childHandler(
              new ChannelInitializer<SocketChannel>() { // (4)
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new TimeServerHandler());
                }
              })
          .option(ChannelOption.SO_BACKLOG, 128) // (5)
          .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

      // Bind and start to accept incoming connections.
      ChannelFuture f = b.bind(port).sync(); // (7)

      // Wait until the server socket is closed.
      // In this example, this does not happen, but you can do that to gracefully
      // shut down your server.
      f.channel().closeFuture().sync();

    } finally {
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }
Esempio n. 8
0
  public static void main(String[] args) throws Exception {

    // 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)
          .childOption(ChannelOption.SO_KEEPALIVE, true)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(new SerializationServerHandlerInitializer());

      // 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();
    }
  }
Esempio n. 9
0
  public void bind(int port) throws Exception {
    // 配置服务端的NIO线程组
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    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) {
                  ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                  ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                  ch.pipeline().addLast(new SubReqServerHandler());
                }
              });

      // 绑定端口,同步等待成功
      ChannelFuture f = b.bind(port).sync();

      // 等待服务端监听端口关闭
      f.channel().closeFuture().sync();
    } finally {
      // 优雅退出,释放线程池资源
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 10
0
  public void run() throws Exception {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .localAddress(new InetSocketAddress(port))
          .childOption(ChannelOption.TCP_NODELAY, true)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(
              new BonaparteNettySslPipelineFactory(
                  1000, new TestServerHandler(), useSsl, false, requirePeerAuthentication, null));

      // Start the server.
      ChannelFuture f = b.bind().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();
    }
  }
Esempio n. 11
0
  public void bind(int port) throws Exception {
    // 配置服务端NIO线程组
    EventLoopGroup boosGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap =
          bootstrap
              .group(boosGroup, workerGroup)
              .channel(NioServerSocketChannel.class)
              .option(ChannelOption.ALLOCATOR.SO_BACKLOG, 100)
              .handler(new LoggingHandler(LogLevel.INFO))
              .childHandler(
                  new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                      ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                      ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
                      ch.pipeline().addLast(new StringDecoder());
                      ch.pipeline().addLast(new EchoServerHandle());
                    }
                  });

      ChannelFuture future = bootstrap.bind(port).sync();
      future.channel().closeFuture().sync();
    } finally {
      boosGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 12
0
  public void run(final int port, final String url) 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 {
                  ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                  ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                  ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                  ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                  ch.pipeline().addLast("fileServerhandler", new HttpFileServerHandler(url));
                }
              });
      ChannelFuture future = b.bind("127.0.0.1", port).sync();
      System.out.println("HTTP Server start");
      future.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 13
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();
    }
  }
Esempio n. 14
0
  @Override
  public void bind(SocketAddress address) throws IOException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      /*
       * Create the bootstrap group
       */
      bootstrap
          .group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new NettyChannelInitializer(new NettyChannelHandler(this)))
          .option(ChannelOption.SO_BACKLOG, 128)
          .childOption(ChannelOption.SO_KEEPALIVE, true);

      /*
       * Bind and start to accept incoming connections.
       */
      ChannelFuture f = bootstrap.bind(address).sync();

      /*
       * Wait until the server socket is closed to shut down the server
       */
      f.channel().closeFuture().sync();
    } catch (InterruptedException ex) {
      throw new IOException("could not start server", ex);
    } finally {
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }
Esempio n. 15
0
 @AfterClass
 public static void destroy() {
   groupA.shutdownGracefully();
   groupB.shutdownGracefully();
   groupA.terminationFuture().syncUninterruptibly();
   groupB.terminationFuture().syncUninterruptibly();
 }
  @Override
  public void Run(int port) {
    EventLoopGroup boss = null;
    EventLoopGroup work = null;
    ServerBootstrap bootStrap = null;
    ChannelFuture future = null;

    try {
      boss = new NioEventLoopGroup();
      work = new NioEventLoopGroup();
      bootStrap = new ServerBootstrap();

      // server setting
      bootStrap.group(boss, work);
      bootStrap.channel(NioServerSocketChannel.class);
      bootStrap.childHandler(new StringServerChannelInit());
      bootStrap.option(ChannelOption.SO_BACKLOG, 128);
      bootStrap.option(ChannelOption.TCP_NODELAY, true);
      bootStrap.childOption(ChannelOption.SO_KEEPALIVE, true);

      // server start
      future = bootStrap.bind(port).sync();

      // server shutdown
      future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      boss.shutdownGracefully();
      work.shutdownGracefully();
    }
  }
Esempio n. 17
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();
    }
  }
  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();
    }
  }
Esempio n. 19
0
 public void stop() {
   try {
     bossGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS);
     workerGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS);
     channel.close();
     // wait for socket to be released
     TimeUnit.MILLISECONDS.sleep(500);
   } catch (Exception ie) {
     logger.trace("Exception while stopping MockServer proxy", ie);
   }
 }
Esempio n. 20
0
  public void stop() {
    if (m_workerGroup == null) {
      throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
    }
    if (m_bossGroup == null) {
      throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
    }
    m_workerGroup.shutdownGracefully();
    m_bossGroup.shutdownGracefully();

    LOG.info("Closed boss and worker Event loops");
    System.out.println("Server stopped");
  }
  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();
    }
  }
Esempio n. 22
0
  public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .childHandler(new TelnetServerInitializer());

      b.bind(port).sync().channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
Esempio n. 23
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();
    }
  }
Esempio n. 24
0
  /**
   * Set up a primary server or back up server.
   *
   * @param port
   * @param isSlave
   * @throws InterruptedException
   */
  public static void init(int port, boolean isBackup) throws InterruptedException {
    MazeServerHandler.isBackup = isBackup;

    if (isBackup) {
      logger.info("[CREATE_SERVER_BACKUP]: {}", port);
    } else {
      logger.info("[CREATE_SERVER_PRIMARY]: {}", port);
    }

    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
                public void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline pipe = ch.pipeline();

                  // Decoders
                  pipe.addLast(
                      "frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
                  pipe.addLast("bytesDecoder", new ByteArrayDecoder());
                  pipe.addLast("messageDecoder", new MazeMessageDecoder());

                  // Encoder
                  pipe.addLast("frameEncoder", new LengthFieldPrepender(4));
                  pipe.addLast("bytesEncoder", new ByteArrayEncoder());
                  pipe.addLast("messageEncoder", new MazeMessageEncoder());

                  // Add Server handler
                  pipe.addLast(new MazeServerHandler());
                }
              })
          .option(ChannelOption.SO_BACKLOG, 128)
          .childOption(ChannelOption.SO_KEEPALIVE, true);

      // Bind and start to accept incoming connections.
      ChannelFuture f = b.bind(port).sync();
      // Wait until the server socket is closed.
      f.channel().closeFuture().sync();
    } finally {
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }
Esempio n. 25
0
  public void connect(int port, String host) throws Exception {
    // 配置客户端NIO线程组
    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(SocketChannel ch) throws Exception {
                  ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                  ch.pipeline()
                      .addLast(
                          new ProtobufDecoder(
                              SubscribeRespProto.SubscribeResp.getDefaultInstance()));
                  ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                  ch.pipeline().addLast(new ProtobufEncoder());
                  ch.pipeline().addLast(new SubReqClientHandler());
                }
              });

      // 发起异步连接操作
      ChannelFuture f = b.connect(host, port).sync();

      // 当代客户端链路关闭
      f.channel().closeFuture().sync();
    } finally {
      // 优雅退出,释放NIO线程组
      group.shutdownGracefully();
    }
  }
Esempio n. 26
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();
   }
 }
Esempio n. 27
0
  public void start() throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(group)
          .channel(NioServerSocketChannel.class)
          .localAddress(new InetSocketAddress(port))
          .childHandler(
              new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                  ch.pipeline()
                      .addLast(new EchoServerHandler())
                      .addFirst(new OutboundTest1())
                      .addFirst(new OutboundTest2());
                }
              });
      ChannelFuture f = b.bind().sync();
      System.out.println(
          EchoServer.class.getName() + " started and listen on" + f.channel().localAddress());
      f.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully().sync();
    }
  }
Esempio n. 28
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();
    }
  }
Esempio n. 29
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();
    }
  }
Esempio n. 30
0
  public void start() throws InterruptedException {
    try {
      eventLoops = new NioEventLoopGroup();

      ServerBootstrap b = new ServerBootstrap();
      b.group(eventLoops);
      b.channel(NioServerSocketChannel.class);
      b.childHandler(
          new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
              channel.pipeline().addLast(new FramePrepender());
              channel.pipeline().addLast(new FrameDecoder());
              channel.pipeline().addLast(new PacketEncoder());
              channel.pipeline().addLast(new PacketDecoder());
              channel.pipeline().addLast(new ServerConnectionHandler(channel));
            }
          });
      ChannelFuture f = b.bind(port).sync();

      f.channel().closeFuture().sync();
    } finally {
      eventLoops.shutdownGracefully();
    }
  }