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 {
     try {
         // TODO Auto-generated method stub
         EventLoopGroup workergroup = new NioEventLoopGroup();
         
         ServerBootstrap bootstrap = new ServerBootstrap();
         bootstrap.group(workergroup);
         bootstrap.channel(NioServerSocketChannel.class);
         // bootstrap.handler(new MyHandler());
         bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel ch) throws Exception {
                 // TODO Auto-generated method stub
                 ChannelPipeline p = ch.pipeline();
                 p.addLast(new HttpRequestDecoder());
                 p.addLast(new HttpResponseEncoder());
                 p.addLast(new MyHandler());
             }
         });
         ChannelFuture f = bootstrap.bind(80).sync();
         f.channel().closeFuture().sync();
         workergroup.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
  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();
    }
  }
 public void start() {
   EventLoopGroup group = new NioEventLoopGroup();
   try {
     ServerBootstrap bootStrap = new ServerBootstrap();
     bootStrap
         .group(group)
         .channel(NioServerSocketChannel.class)
         .localAddress(new InetSocketAddress(port))
         .childHandler(new WebSocketServerInitializer());
     ChannelFuture future = bootStrap.bind().sync();
     System.out.println(
         WebSocketServer.class.getSimpleName()
             + " started and listen on "
             + future.channel().localAddress());
     future.channel().closeFuture().sync();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       group.shutdownGracefully().sync();
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
Example #5
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();
    }
  }
Example #6
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();
    }
  }
Example #7
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();
    }
  }
  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();
    }
  }
Example #9
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();
    }
  }
Example #10
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();
    }
  }
  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();
    }
  }
Example #12
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();
    }
  }
Example #13
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();
    }
  }
Example #14
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();
    }
  }
Example #15
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();
    }
  }
  @BeforeClass
  public static void init() {
    // Configure a test server
    group = new LocalEventLoopGroup();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(group)
        .channel(LocalServerChannel.class)
        .childHandler(
            new ChannelInitializer<LocalChannel>() {
              @Override
              public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline()
                    .addLast(
                        new ChannelInboundHandlerAdapter() {
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                          }
                        });
              }
            });

    localAddr =
        (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress();
  }
Example #17
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();
    }
  }
Example #18
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();
    }
  }
  public TextLineServer() {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);
    b.channel(NioServerSocketChannel.class);
    b.childHandler(
        new ChannelInitializer<SocketChannel>() {
          @Override
          public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            //                pipeline.addLast("frameDecoder", new
            // LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            //                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new NettyHandler());
          }
        });

    try {
      b.bind(IP, PORT).sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    logger.info("TCP服务器已启动");
    System.out.println("--------------------------------------------------");
    System.out.println("Server Started");
    System.out.println("--------------------------------------------------");
  }
Example #20
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();
    }
  }
Example #21
0
  @Override
  protected ServerBootstrap buildBootstrap(final EventLoopGroup group) {
    final RedisRequestHandler commandHandler = new RedisRequestHandler(redisServer);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap
        .group(group, group)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 100)
        .localAddress(new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()))
        .childOption(ChannelOption.TCP_NODELAY, true)
        .childHandler(
            new ChannelInitializer<SocketChannel>() {

              @Override
              protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // p.addLast(new LoggingHandler(LogLevel.DEBUG));
                p.addLast(new RedisRequestDecoder());
                p.addLast(new RedisResponseEncoder());
                p.addLast(group, commandHandler);
              }
            });

    return serverBootstrap;
  }
Example #22
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();
    }
  }
  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();
    }
  }
Example #24
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();
    }
  }
Example #25
0
 @Override
 public void start() throws Exception {
   server
       .group(new NioEventLoopGroup(), new NioEventLoopGroup())
       .channel(NioServerSocketChannel.class)
       .localAddress(port)
       .childHandler(new HttpProxyServerInitializer());
   server.bind().sync().channel().closeFuture().sync();
 }
Example #26
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");
   }
 }
  private void testSpdyEcho(int version) throws Throwable {
    ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor));
    ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor));

    ChannelBuffer frames = createFrames(version);

    EchoHandler sh = new EchoHandler(frames, true);
    EchoHandler ch = new EchoHandler(frames, false);

    sb.getPipeline().addLast("decoder", new SpdyFrameDecoder(version));
    sb.getPipeline().addLast("encoder", new SpdyFrameEncoder(version));
    sb.getPipeline().addLast("handler", sh);

    cb.getPipeline().addLast("handler", ch);

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(InetAddress.getLocalHost(), port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());

    Channel cc = ccf.getChannel();
    cc.write(frames);

    while (ch.counter < frames.writerIndex() - ignoredBytes) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
  @Override
  public void afterPropertiesSet() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new DiamondServerInitializer(serverHandler));

    b.bind(port).sync().channel();
    logger.info("启动 Diamond Netty Server");
  }
 @After
 public void teardown() throws Exception {
   serverChannel.close().sync();
   Future<?> serverGroup = sb.group().shutdownGracefully(0, 0, MILLISECONDS);
   Future<?> serverChildGroup = sb.childGroup().shutdownGracefully(0, 0, MILLISECONDS);
   Future<?> clientGroup = cb.group().shutdownGracefully(0, 0, MILLISECONDS);
   serverGroup.sync();
   serverChildGroup.sync();
   clientGroup.sync();
 }
Example #30
0
 @Override
 public void close() throws IOException {
   int quietPeriodSecs = mTachyonConf.getInt(Constants.WORKER_NETWORK_NETTY_SHUTDOWN_QUIET_PERIOD);
   int timeoutSecs = mTachyonConf.getInt(Constants.WORKER_NETWORK_NETTY_SHUTDOWN_TIMEOUT);
   // TODO(binfan): investigate when timeoutSecs is zero (e.g., set in integration tests), does
   // this still complete successfully.
   mChannelFuture.channel().close().awaitUninterruptibly(timeoutSecs, TimeUnit.SECONDS);
   mBootstrap.group().shutdownGracefully(quietPeriodSecs, timeoutSecs, TimeUnit.SECONDS);
   mBootstrap.childGroup().shutdownGracefully(quietPeriodSecs, timeoutSecs, TimeUnit.SECONDS);
 }