コード例 #1
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();
    }
  }
コード例 #2
0
 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();
     }
 }
コード例 #3
0
  @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();
    }
  }
コード例 #4
0
  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("--------------------------------------------------");
  }
コード例 #5
0
  public synchronized void start(String host, int port, final boolean sasl) throws Exception {
    this.host = host;
    this.port = port;
    this.sasl = sasl;

    if (channelClazz != null) {
      // Already started
      return;
    }

    int threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
    channelClazz = NioServerSocketChannel.class;
    eventLoopGroup =
        new NioEventLoopGroup(
            threadsToUse,
            new SimpleServerThreadFactory(
                "simple-server", true, Thread.currentThread().getContextClassLoader()));

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);

    ChannelInitializer<Channel> factory =
        new ChannelInitializer<Channel>() {
          @Override
          public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("amqp-handler", new ProtocolDecoder());
          }
        };
    bootstrap.childHandler(factory);

    bootstrap
        .option(ChannelOption.SO_REUSEADDR, true)
        .childOption(ChannelOption.SO_REUSEADDR, true)
        .childOption(ChannelOption.SO_KEEPALIVE, true)
        .
        //       childOption(ChannelOption.AUTO_READ, false).
        childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    channelGroup =
        new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup =
        new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    SocketAddress address;
    address = new InetSocketAddress(host, port);
    Channel serverChannel = bootstrap.bind(address).syncUninterruptibly().channel();
    serverChannelGroup.add(serverChannel);
  }
コード例 #6
0
ファイル: Server.java プロジェクト: hyy044101331/mkResin
  /** Æô¶¯master */
  public static void startMaster() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(bossGroup, workerGroup);
      bootstrap.channel(NioServerSocketChannel.class);
      bootstrap.option(ChannelOption.SO_BACKLOG, 128);
      bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
      bootstrap.childHandler(new MasterChannelInitializer());

      bootstrap.bind(Constant.NOTIFY_PORT).sync();
    } catch (InterruptedException e) {
      log.error("interrupt", e);
      workerGroup.shutdownGracefully();
      bossGroup.shutdownGracefully();
    }
  }
コード例 #7
0
    public void run() {
      // construct boss and worker threads (num threads = number of cores)

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

      try {
        ServerBootstrap b = new ServerBootstrap();
        bootstrap.put(conf.getPort(), b);

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR);

        boolean compressComm = false;
        b.childHandler(new ServerInitializer(compressComm));

        // Start the server.
        logger.info(
            "Starting server " + conf.getNodeId() + ", listening on port = " + conf.getPort());
        ChannelFuture f = b.bind(conf.getPort()).syncUninterruptibly();

        // should use a future channel listener to do this step
        // allChannels.add(f.channel());

        // block until the server socket is closed.
        f.channel().closeFuture().sync();
      } catch (Exception ex) {
        // on bind().sync()
        logger.error("Failed to setup public handler.", ex);
      } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
      }

      // We can also accept connections from a other ports (e.g., isolate
      // read
      // and writes)
    }
コード例 #8
0
  private void bootstrapEnv(
      int dataCountDown, int settingsAckCount, int requestCountDown, int trailersCountDown)
      throws Exception {
    requestLatch = new CountDownLatch(requestCountDown);
    serverSettingsAckLatch = new CountDownLatch(settingsAckCount);
    dataLatch = new CountDownLatch(dataCountDown);
    trailersLatch = new CountDownLatch(trailersCountDown);
    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            serverFrameCountDown =
                new FrameCountDown(
                    serverListener, serverSettingsAckLatch, requestLatch, dataLatch, trailersLatch);
            p.addLast(new Http2ConnectionHandler(true, serverFrameCountDown));
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new Http2ConnectionHandler(false, clientListener));
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    http2Client = clientChannel.pipeline().get(Http2ConnectionHandler.class);
  }
コード例 #9
0
  @Before
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    requestLatch = new CountDownLatch(1);
    frameWriter = new DefaultHttp2FrameWriter();
    dataCaptor = ArgumentCaptor.forClass(ByteBuf.class);

    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("reader", new FrameAdapter(serverObserver));
            p.addLast(Http2CodecUtil.ignoreSettingsHandler());
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("reader", new FrameAdapter(null));
            p.addLast(Http2CodecUtil.ignoreSettingsHandler());
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
  }
コード例 #10
0
ファイル: Application.java プロジェクト: silabsoft/mopar
  /**
   * Starts the server.
   *
   * @param address The socket address to bind.
   * @throws IOException An I/O exception was encountered while binding the socket.
   */
  public void start(SocketAddress address) throws IOException {
    setup();

    try {
      ServerBootstrap bootstrap = new ServerBootstrap();
      NioEventLoopGroup parentGroup = new NioEventLoopGroup();
      NioEventLoopGroup childGroup = new NioEventLoopGroup();
      ChannelFuture sync =
          bootstrap
              .channel(NioServerSocketChannel.class)
              .group(parentGroup, childGroup)
              .childHandler(new ServerChannelInitializer(this))
              .bind(address)
              .sync();
      channel = sync.channel();
      logger.info("Server started on " + address);
    } catch (InterruptedException ex) {
      throw new IOException("Failed to bind the server address " + address, ex);
    }
  }
コード例 #11
0
    public void run() {
      // construct boss and worker threads (num threads = number of cores)

      // UDP: not a good option as the message will be dropped

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

      try {
        ServerBootstrap b = new ServerBootstrap();
        bootstrap.put(conf.getMgmtPort(), b);

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.option(ChannelOption.TCP_NODELAY, true);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        // b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR);

        boolean compressComm = false;
        b.childHandler(new ManagementInitializer(compressComm));

        // Start the server.

        logger.info(
            "Starting mgmt " + conf.getNodeId() + ", listening on port = " + conf.getMgmtPort());
        ChannelFuture f = b.bind(conf.getMgmtPort()).syncUninterruptibly();

        // block until the server socket is closed.
        f.channel().closeFuture().sync();
      } catch (Exception ex) {
        // on bind().sync()
        logger.error("Failed to setup public handler.", ex);
      } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
      }
    }
コード例 #12
0
ファイル: NettyServer.java プロジェクト: 1011641270/Java
  public void bing(int port) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workGroup = new NioEventLoopGroup();

    try {

      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workGroup);
      b.channel(NioServerSocketChannel.class);
      b.option(ChannelOption.SO_BACKLOG, 1024);
      b.childHandler(new ChildChannelHandler());

      // 绑定端口
      ChannelFuture f = b.bind(port).sync();
      // 等待服务端监听端口关闭
      f.channel().closeFuture().sync();

    } finally {
      bossGroup.shutdownGracefully();
      workGroup.shutdownGracefully();
    }
  }
コード例 #13
0
  @Before
  public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);

    clientDelegator = null;
    serverDelegator = null;
    serverConnectedChannel = null;
    maxContentLength = 1024;
    setServerLatch(1);
    setClientLatch(1);
    frameWriter = new DefaultHttp2FrameWriter();

    sb = new ServerBootstrap();
    cb = new Bootstrap();

    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(true);
            p.addLast(
                "reader",
                new HttpAdapterFrameAdapter(
                    connection,
                    InboundHttp2ToHttpPriorityAdapter.newInstance(connection, maxContentLength),
                    new CountDownLatch(10)));
            serverDelegator = new HttpResponseDelegator(serverListener, serverLatch);
            p.addLast(serverDelegator);
            serverConnectedChannel = ch;
          }
        });

    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(
        new ChannelInitializer<Channel>() {
          @Override
          protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            Http2Connection connection = new DefaultHttp2Connection(false);
            p.addLast(
                "reader",
                new HttpAdapterFrameAdapter(
                    connection,
                    InboundHttp2ToHttpPriorityAdapter.newInstance(connection, maxContentLength),
                    new CountDownLatch(10)));
            clientDelegator = new HttpResponseDelegator(clientListener, clientLatch);
            p.addLast(clientDelegator);
          }
        });

    serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
    int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
  }
コード例 #14
0
  public synchronized void start() throws Exception {
    if (channelClazz != null) {
      // Already started
      return;
    }

    if (useInvm) {
      channelClazz = LocalServerChannel.class;
      eventLoopGroup = new LocalEventLoopGroup();
    } else {
      int threadsToUse;

      if (nioRemotingThreads == -1) {
        // Default to number of cores * 3

        threadsToUse = Runtime.getRuntime().availableProcessors() * 3;
      } else {
        threadsToUse = this.nioRemotingThreads;
      }
      channelClazz = NioServerSocketChannel.class;
      eventLoopGroup =
          new NioEventLoopGroup(
              threadsToUse,
              new ActiveMQThreadFactory("activemq-netty-threads", true, getThisClassLoader()));
    }

    bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(channelClazz);
    final SSLContext context;
    if (sslEnabled) {
      try {
        if (keyStorePath == null
            && TransportConstants.DEFAULT_TRUSTSTORE_PROVIDER.equals(keyStoreProvider))
          throw new IllegalArgumentException(
              "If \""
                  + TransportConstants.SSL_ENABLED_PROP_NAME
                  + "\" is true then \""
                  + TransportConstants.KEYSTORE_PATH_PROP_NAME
                  + "\" must be non-null "
                  + "unless an alternative \""
                  + TransportConstants.KEYSTORE_PROVIDER_PROP_NAME
                  + "\" has been specified.");
        context =
            SSLSupport.createContext(
                keyStoreProvider,
                keyStorePath,
                keyStorePassword,
                trustStoreProvider,
                trustStorePath,
                trustStorePassword);
      } catch (Exception e) {
        IllegalStateException ise =
            new IllegalStateException("Unable to create NettyAcceptor for " + host + ":" + port);
        ise.initCause(e);
        throw ise;
      }
    } else {
      context = null; // Unused
    }

    final AtomicBoolean warningPrinted = new AtomicBoolean(false);

    ChannelInitializer<Channel> factory =
        new ChannelInitializer<Channel>() {
          @Override
          public void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (sslEnabled) {
              SSLEngine engine = context.createSSLEngine();

              engine.setUseClientMode(false);

              if (needClientAuth) engine.setNeedClientAuth(true);

              // setting the enabled cipher suites resets the enabled protocols so we need
              // to save the enabled protocols so that after the customer cipher suite is enabled
              // we can reset the enabled protocols if a customer protocol isn't specified
              String[] originalProtocols = engine.getEnabledProtocols();

              if (enabledCipherSuites != null) {
                try {
                  engine.setEnabledCipherSuites(
                      SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
                } catch (IllegalArgumentException e) {
                  ActiveMQServerLogger.LOGGER.invalidCipherSuite(
                      SSLSupport.parseArrayIntoCommandSeparatedList(
                          engine.getSupportedCipherSuites()));
                  throw e;
                }
              }

              if (enabledProtocols != null) {
                try {
                  engine.setEnabledProtocols(
                      SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
                } catch (IllegalArgumentException e) {
                  ActiveMQServerLogger.LOGGER.invalidProtocol(
                      SSLSupport.parseArrayIntoCommandSeparatedList(
                          engine.getSupportedProtocols()));
                  throw e;
                }
              } else {
                engine.setEnabledProtocols(originalProtocols);
              }

              // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
              // This recommendation came from
              // http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
              String[] protocols = engine.getEnabledProtocols();
              Set<String> set = new HashSet<>();
              for (String s : protocols) {
                if (s.equals("SSLv3") || s.equals("SSLv2Hello")) {
                  if (!warningPrinted.get()) {
                    ActiveMQServerLogger.LOGGER.disallowedProtocol(s);
                  }
                  continue;
                }
                set.add(s);
              }
              warningPrinted.set(true);
              engine.setEnabledProtocols(set.toArray(new String[0]));

              SslHandler handler = new SslHandler(engine);

              pipeline.addLast("ssl", handler);
            }
            pipeline.addLast(protocolHandler.getProtocolDecoder());
          }
        };
    bootstrap.childHandler(factory);

    // Bind
    bootstrap.childOption(ChannelOption.TCP_NODELAY, tcpNoDelay);
    if (tcpReceiveBufferSize != -1) {
      bootstrap.childOption(ChannelOption.SO_RCVBUF, tcpReceiveBufferSize);
    }
    if (tcpSendBufferSize != -1) {
      bootstrap.childOption(ChannelOption.SO_SNDBUF, tcpSendBufferSize);
    }
    if (backlog != -1) {
      bootstrap.option(ChannelOption.SO_BACKLOG, backlog);
    }
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
    channelGroup =
        new DefaultChannelGroup("activemq-accepted-channels", GlobalEventExecutor.INSTANCE);

    serverChannelGroup =
        new DefaultChannelGroup("activemq-acceptor-channels", GlobalEventExecutor.INSTANCE);

    if (httpUpgradeEnabled) {
      // the channel will be bound by the Web container and hand over after the HTTP Upgrade
      // handshake is successful
    } else {
      startServerChannels();

      paused = false;

      if (notificationService != null) {
        TypedProperties props = new TypedProperties();
        props.putSimpleStringProperty(
            new SimpleString("factory"), new SimpleString(NettyAcceptorFactory.class.getName()));
        props.putSimpleStringProperty(new SimpleString("host"), new SimpleString(host));
        props.putIntProperty(new SimpleString("port"), port);
        Notification notification =
            new Notification(null, CoreNotificationType.ACCEPTOR_STARTED, props);
        notificationService.sendNotification(notification);
      }

      if (batchDelay > 0) {
        flusher = new BatchFlusher();

        batchFlusherFuture =
            scheduledThreadPool.scheduleWithFixedDelay(
                flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS);
      }

      ActiveMQServerLogger.LOGGER.startedAcceptor(host, port, protocolsString);
    }
  }