Java Code Examples for io.netty.bootstrap.ServerBootstrap

The following examples show how to use io.netty.bootstrap.ServerBootstrap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: incubator-pinot   Source File: QueryServer.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {
  _bossGroup = new NioEventLoopGroup();
  _workerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    _channel = serverBootstrap.group(_bossGroup, _workerGroup).channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
        .childHandler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ch.pipeline()
                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, Integer.BYTES, 0, Integer.BYTES),
                    new LengthFieldPrepender(Integer.BYTES),
                    new InstanceRequestHandler(_queryScheduler, _serverMetrics));
          }
        }).bind(_port).sync().channel();
  } catch (Exception e) {
    // Shut down immediately
    _workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
    _bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
    throw new RuntimeException(e);
  }
}
 
Example 2
Source Project: disthene   Source File: CarbonServer.java    License: MIT License 6 votes vote down vote up
public void run() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new DelimiterBasedFrameDecoder(MAX_FRAME_LENGTH, false, Delimiters.lineDelimiter()));
                    p.addLast(new CarbonServerHandler(bus, configuration.getCarbon().getBaseRollup()));
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    logger.error(cause);
                    super.exceptionCaught(ctx, cause);
                }
            });

    // Start the server.
    b.bind(configuration.getCarbon().getBind(), configuration.getCarbon().getPort()).sync();
}
 
Example 3
Source Project: krpc   Source File: SelfCheckHttpServer.java    License: Apache License 2.0 6 votes vote down vote up
public void init() {

        bossGroup = new NioEventLoopGroup(1, bossThreadFactory);
        workerGroup = new NioEventLoopGroup(workerThreads, workThreadFactory);

        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("timeout", new IdleStateHandler(0, 0, idleSeconds));
                        pipeline.addLast("codec", new HttpServerCodec(maxInitialLineLength, maxHeaderSize, maxChunkSize));
                        pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
                        pipeline.addLast("compressor", new HttpContentCompressor());
                        pipeline.addLast("handler", SelfCheckHttpServer.this);
                    }
                });
        serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);
        serverBootstrap.option(ChannelOption.SO_BACKLOG, backlog);
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        // serverBootstrap.childOption(ChannelOption.SO_RCVBUF, 65536);
    }
 
Example 4
Source Project: netty.book.kor   Source File: TelnetServer.java    License: MIT License 6 votes vote down vote up
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)
				.handler(new LoggingHandler(LogLevel.INFO))
				.childHandler(new TelnetServerInitializer());

		ChannelFuture future = b.bind(PORT).sync();
		future.channel().closeFuture().sync();
	}
	finally {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}
}
 
Example 5
Source Project: netty-learning   Source File: CustomService.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {


        EventLoopGroup boss = new NioEventLoopGroup() ;
        EventLoopGroup work = new NioEventLoopGroup() ;

        try {

            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(PORT))
                    .childHandler(new CustomInitializer())
                    ;

            ChannelFuture future = bootstrap.bind().sync();
            future.channel().closeFuture().sync() ;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully() ;
            work.shutdownGracefully() ;
        }
    }
 
Example 6
Source Project: netty.book.kor   Source File: DiscardServer.java    License: MIT License 6 votes vote down vote up
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)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new DiscardServerHandler());
            }
       });

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

        f.channel().closeFuture().sync();
    }
    finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example 7
Source Project: atomix   Source File: NettyMessagingService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Bootstraps a server.
 *
 * @return a future to be completed once the server has been bound to all interfaces
 */
private CompletableFuture<Void> bootstrapServer() {
  ServerBootstrap b = new ServerBootstrap();
  b.option(ChannelOption.SO_REUSEADDR, true);
  b.option(ChannelOption.SO_BACKLOG, 128);
  b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
      new WriteBufferWaterMark(8 * 1024, 32 * 1024));
  b.childOption(ChannelOption.SO_RCVBUF, 1024 * 1024);
  b.childOption(ChannelOption.SO_SNDBUF, 1024 * 1024);
  b.childOption(ChannelOption.SO_KEEPALIVE, true);
  b.childOption(ChannelOption.TCP_NODELAY, true);
  b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
  b.group(serverGroup, clientGroup);
  b.channel(serverChannelClass);
  if (enableNettyTls) {
    try {
      b.childHandler(new SslServerChannelInitializer());
    } catch (SSLException e) {
      return Futures.exceptionalFuture(e);
    }
  } else {
    b.childHandler(new BasicServerChannelInitializer());
  }
  return bind(b);
}
 
Example 8
Source Project: netty-zmtp   Source File: ProtocolViolationTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  final ServerBootstrap serverBootstrap = new ServerBootstrap();
  serverBootstrap.channel(NioServerSocketChannel.class);
  bossGroup = new NioEventLoopGroup(1);
  group = new NioEventLoopGroup();
  serverBootstrap.group(bossGroup, group);
  serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
    @Override
    protected void initChannel(final NioSocketChannel ch) throws Exception {
      ch.pipeline().addLast(
          ZMTPCodec.builder()
              .protocol(ZMTP20)
              .socketType(ROUTER)
              .localIdentity(identity)
              .build(),
          mockHandler);
    }
  });

  serverChannel = serverBootstrap.bind(new InetSocketAddress("localhost", 0))
      .awaitUninterruptibly().channel();
  serverAddress = (InetSocketAddress) serverChannel.localAddress();
}
 
Example 9
Source Project: smartacus-mqtt-broker   Source File: HttpServer.java    License: Apache License 2.0 6 votes vote down vote up
public void run() throws Exception{
    EventLoopGroup bossGroup=new NioEventLoopGroup(1);
    NioEventLoopGroup  workerGroup=new NioEventLoopGroup();
    try{
        //实例化session工厂和connection工厂
        ServerBootstrap sboot=new ServerBootstrap();
        sboot.group(bossGroup,workerGroup)
                //设置通道类型
                .channel(NioServerSocketChannel.class)
                //向通道的中添加handler初始化器
                .childHandler(new HttpChannelChannelInitializer())
                .option(ChannelOption.SO_BACKLOG,64)
                //设置子Socket的keepalive时间
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        //绑定端口号
        ChannelFuture cf = sboot.bind(18088).sync();
        cf.channel().closeFuture().sync();
    }finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example 10
Source Project: mini-dubbo   Source File: NettyServer.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
 
Example 11
Source Project: java-study   Source File: NettyServerDemo3.java    License: Apache License 2.0 6 votes vote down vote up
public void start(){  
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try {  
            ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
                    .childHandler(new ChannelInitializer<SocketChannel>() {  
                          
                        protected void initChannel(SocketChannel ch) throws Exception {  
                             ch.pipeline().addLast(new NettyDecoder2(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));  
//                             ch.pipeline().addLast(new NettyDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));  
                             ch.pipeline().addLast(new NettyServerHandlerDemo3());  
                        };  
                          
                    }).option(ChannelOption.SO_BACKLOG, 128)     
                    .childOption(ChannelOption.SO_KEEPALIVE, true);  
             // 绑定端口,开始接收进来的连接  
             ChannelFuture future = sbs.bind(port).sync();    
               
             System.out.println("Netty服务端成功启动!端口为: " + port );  
             future.channel().closeFuture().sync();  
        } catch (Exception e) {  
            bossGroup.shutdownGracefully();  
            workerGroup.shutdownGracefully();  
        }  
    }
 
Example 12
Source Project: yuzhouwan   Source File: EchoServer.java    License: Apache License 2.0 6 votes vote down vote up
public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap(); // 引导辅助程序
    EventLoopGroup group = new NioEventLoopGroup(); // 通过 nio 的方式接受连接和处理连接
    try {
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class) //设置 nio 类型的 channel
                .localAddress(new InetSocketAddress(port)) // 设置监听端口
                .childHandler(new ChannelInitializer<SocketChannel>() { // 有连接到达时会创建一个 channel
                    // pipeline 管理 channel 中的 handler,在 channel 队列中添加一个 handler 来处理业务
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("myHandler", new EchoServerHandler());
                        // ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(0, 0, 180));
                    }
                });
        ChannelFuture future = bootstrap.bind().sync(); //配置完成,绑定 server,并通过 sync 同步方法阻塞直到绑定成功
        System.out.println(EchoServer.class.getName() + " started and listen on " + future.channel().localAddress());
        future.channel().closeFuture().sync(); // 应用程序会一直等待,直到 channel 关闭
    } finally {
        group.shutdownGracefully().sync();
    }
}
 
Example 13
Source Project: neoscada   Source File: Receiver.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Receiver ( final ReceiverHandlerFactory factory, final SocketAddress addr )
{
    this.factory = factory;

    this.bossGroup = new NioEventLoopGroup ();
    this.workerGroup = new NioEventLoopGroup ();
    this.bootstrap = new ServerBootstrap ();
    this.bootstrap.group ( this.bossGroup, this.workerGroup );
    this.bootstrap.channel ( NioServerSocketChannel.class );
    this.bootstrap.option ( ChannelOption.SO_BACKLOG, 5 );
    this.bootstrap.option ( ChannelOption.SO_REUSEADDR, true );
    this.bootstrap.childHandler ( new ChannelInitializer<SocketChannel> () {

        @Override
        protected void initChannel ( final SocketChannel ch ) throws Exception
        {
            handleInitChannel ( ch );
        }
    } );

    this.channel = this.bootstrap.bind ( addr ).channel ();

    logger.info ( "Receiver running ..." );
}
 
Example 14
Source Project: Lottor   Source File: EchoServer.java    License: MIT License 6 votes vote down vote up
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group) // 绑定线程池
                .channel(NioServerSocketChannel.class) // 指定使用的channel
                .localAddress(this.port)// 绑定监听端口
                .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected...; Client:" + ch.remoteAddress());
                        ch.pipeline().addLast(new EchoServerHandler()); // 客户端触发操作
                    }
                });
        ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
        System.out.println(EchoServer.class + " started and listen on " + cf.channel().localAddress());
        cf.channel().closeFuture().sync(); // 关闭服务器通道
    } finally {
        group.shutdownGracefully().sync(); // 释放线程池资源
    }
}
 
Example 15
Source Project: momo-cloud-permission   Source File: TCPServer.java    License: Apache License 2.0 6 votes vote down vote up
ChannelFuture bing() {
    ChannelFuture channelFuture = null;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)    //非阻塞模式
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, keepAlive)
                .option(ChannelOption.SO_BACKLOG, backlog)
                .childHandler(new WSServerInitialzer(nettyHandlerService));

        channelFuture = b.bind(new InetSocketAddress(tcpPort)).syncUninterruptibly();
        channel = channelFuture.channel();
    } catch (Exception e) {
        log.error("netty start error {}  {}", e.getMessage(), e);
    } finally {
        if (null != channelFuture && channelFuture.isSuccess()) {
            log.info("tCPServerTwo start ok");
        } else {
            log.error("tCPServerTwo start error ");
        }
    }
    return channelFuture;
}
 
Example 16
Source Project: netty-cookbook   Source File: BootstrapTemplate.java    License: Apache License 2.0 6 votes vote down vote up
public static void newServerBootstrap(String host, int port, ChannelInitializer<SocketChannel> initializer){
	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(initializer)
            .bind(port).sync().channel().closeFuture().sync();	        
       } catch (Exception e){   
       	e.printStackTrace();
       } 
       finally {
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
       }
}
 
Example 17
Source Project: jforgame   Source File: NettySocketServer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
	public void start() throws Exception {
		int serverPort = ServerConfig.getInstance().getServerPort();
		logger.info("netty socket服务已启动,正在监听用户的请求@port:" + serverPort + "......");
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			b.bind(new InetSocketAddress(serverPort)).sync();
//			f.channel().closeFuture().sync();
		} catch (Exception e) {
			logger.error("", e);

			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();

			throw e;
		}
	}
 
Example 18
Source Project: xraft   Source File: Server.java    License: MIT License 6 votes vote down vote up
public void start() throws Exception {
    this.node.start();

    ServerBootstrap serverBootstrap = new ServerBootstrap()
            .group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new Encoder());
                    pipeline.addLast(new Decoder());
                    pipeline.addLast(new ServiceHandler(service));
                }
            });
    logger.info("server started at port {}", this.port);
    serverBootstrap.bind(this.port);
}
 
Example 19
@Override
public List<BootstrapFactory<ServerBootstrap>> serverSocket() {
    return Arrays.asList(
            new BootstrapFactory<ServerBootstrap>() {
                @Override
                public ServerBootstrap newInstance() {
                    return new ServerBootstrap().group(EPOLL_BOSS_GROUP, EPOLL_WORKER_GROUP)
                            .channel(EpollServerSocketChannel.class);
                }
            },
            new BootstrapFactory<ServerBootstrap>() {
                @Override
                public ServerBootstrap newInstance() {
                    return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup)
                            .channel(NioServerSocketChannel.class);
                }
            }
    );
}
 
Example 20
Source Project: krpc   Source File: TcpServer.java    License: MIT License 6 votes vote down vote up
protected static void run() throws Exception {
		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 ByteArrayDecoder());
				pipeline.addLast("encoder", new ByteArrayEncoder());
//				pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//				pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
				pipeline.addLast(new TcpServerHandler());
			}
		});

		// b.bind(IP, PORT).sync();
		ChannelFuture f = b.bind(PORT).sync(); // (7)

		f.channel().closeFuture().sync();

		System.out.println("TCP服务器已启动");
	}
 
Example 21
Source Project: newts   Source File: GraphiteListener.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
    try {
        ServerBootstrap bStrap = new ServerBootstrap();
        bStrap.group(m_bossGroup, m_workerGroup);
        bStrap.channel(NioServerSocketChannel.class);
        bStrap.handler(new LoggingHandler(LogLevel.INFO));
        bStrap.childHandler(m_initializer);
        Channel ch = bStrap.bind(this.m_listen).sync().channel();

        ch.closeFuture().sync();
    }
    catch (InterruptedException e) {
        LOG.info("Interrupted; Shutting down!");
    }
    finally {
        m_bossGroup.shutdownGracefully();
        m_workerGroup.shutdownGracefully();
    }
}
 
Example 22
Source Project: crate   Source File: Netty4Transport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressForbidden(reason = "debug")
protected void stopInternal() {
    Releasables.close(() -> {
        final List<Tuple<String, Future<?>>> serverBootstrapCloseFutures = new ArrayList<>(serverBootstraps.size());
        for (final Map.Entry<String, ServerBootstrap> entry : serverBootstraps.entrySet()) {
            serverBootstrapCloseFutures.add(
                Tuple.tuple(entry.getKey(), entry.getValue().config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS)));
        }
        for (final Tuple<String, Future<?>> future : serverBootstrapCloseFutures) {
            future.v2().awaitUninterruptibly();
            if (!future.v2().isSuccess()) {
                logger.debug(
                    (Supplier<?>) () -> new ParameterizedMessage(
                        "Error closing server bootstrap for profile [{}]", future.v1()), future.v2().cause());
            }
        }
        serverBootstraps.clear();

        if (clientBootstrap != null) {
            clientBootstrap.config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS).awaitUninterruptibly();
            clientBootstrap = null;
        }
    });
}
 
Example 23
Source Project: netty-restful-server   Source File: NettyRestServer.java    License: MIT License 6 votes vote down vote up
public void start() {
    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(new ServerInitializer());

        Channel ch = b.bind(Config.getInt("server.port")).sync().channel();

        ch.closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 24
Source Project: Lottor   Source File: NettyServerServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 启动netty服务
 */
@Override
public void start() {
    SocketManager.getInstance().setMaxConnection(nettyConfig.getMaxConnection());
    servletExecutor = new DefaultEventExecutorGroup(MAX_THREADS);
    if (nettyConfig.getMaxThreads() != 0) {
        MAX_THREADS = nettyConfig.getMaxThreads();
    }
    try {
        final SerializeProtocolEnum serializeProtocolEnum =
                SerializeProtocolEnum.acquireSerializeProtocol(nettyConfig.getSerialize());

        nettyServerHandlerInitializer.setSerializeProtocolEnum(serializeProtocolEnum);
        nettyServerHandlerInitializer.setServletExecutor(servletExecutor);
        ServerBootstrap b = new ServerBootstrap();
        groups(b, MAX_THREADS << 1);
        b.bind(nettyConfig.getPort());

        LOGGER.info("netty service started on port: " + nettyConfig.getPort());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 25
Source Project: sds   Source File: NettyServerServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void start() {
    bossGroup = new NioEventLoopGroup(); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SocketServerChannelInitializer(socketConfig.getHeartTime(),socketService,applicationContext));
        // Bind and start to accept incoming connections.
        b.bind(socketConfig.getPort());

        logger.info("socket: "+socketConfig.getPort()+" starting....");
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 26
Source Project: netty4.0.27Learn   Source File: HttpHelloWorldServer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpHelloWorldServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 27
@Override
public void start() throws InterruptedException {
    SocketManager.getInstance().setMaxConnection(nettyConfig.getMaxConnection());
    if (nettyConfig.getMaxThreads() != 0) {
        maxThread = nettyConfig.getMaxThreads();
    }
    servletExecutor = new DefaultEventExecutorGroup(maxThread);
    final SerializeProtocolEnum serializeProtocolEnum =
            SerializeProtocolEnum.acquireSerializeProtocol(nettyConfig.getSerialize());
    nettyServerHandlerInitializer.setSerializeProtocolEnum(serializeProtocolEnum);
    nettyServerHandlerInitializer.setServletExecutor(servletExecutor);
    ServerBootstrap b = new ServerBootstrap();
    bossGroup = createEventLoopGroup();
    if (bossGroup instanceof EpollEventLoopGroup) {
        groupsEpoll(b, maxThread);
    } else {
        groupsNio(b, maxThread);
    }
    try {
        LOGGER.info("netty service started on port: " + nettyConfig.getPort());
        ChannelFuture future = b.bind(nettyConfig.getPort()).sync();
        future.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        servletExecutor.shutdownGracefully();
    }

}
 
Example 28
Source Project: dubbo-2.6.5   Source File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    protected void doOpen() throws Throwable {
        bootstrap = new ServerBootstrap();

        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
//        iothreads参数值,默认cpu线程数+1 小于32
        workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
                new DefaultThreadFactory("NettyServerWorker", true));

        final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
        channels = nettyServerHandler.getChannels();

        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                        ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                                .addLast("decoder", adapter.getDecoder())
                                .addLast("encoder", adapter.getEncoder())
                                .addLast("handler", nettyServerHandler);
                    }
                });
        // bind
        ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
        channelFuture.syncUninterruptibly();
        channel = channelFuture.channel();

    }
 
Example 29
Source Project: learning-code   Source File: BaseServerTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public void serverTask(ChannelHandler... channelHandlers) {
    // bossGroup 用来接收进来的连接
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    // boss 接收的连接注册在 worker 上
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // nio 服务启动辅助类
    ServerBootstrap bootstrap = new ServerBootstrap();
    try {
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // 处理一个已经接收的 channel, 自定义事件处理
                .childHandler(handler())
                // 提供 NioServerSocketChannel 用来接收连接的属性设置
                .option(ChannelOption.SO_BACKLOG, 128)
                // 提供父管道 ServerChannel 接收到连接的属性设置
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口,启动,接收进来的连接
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        // 服务器 socket 关闭
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        // 优雅退出
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
 
Example 30
Source Project: lannister   Source File: MqttServer.java    License: Apache License 2.0 5 votes vote down vote up
private void executeBootstrap(ScheduledExecutor scheduledExecutor, int port, boolean useWebSocket, boolean useSsl)
		throws InterruptedException {
	ServerBootstrap bootstrap = new ServerBootstrap();

	Class<? extends ServerChannel> serverChannelClass;

	if (Literals.NETTY_EPOLL.equals(Settings.INSTANCE.nettyTransportMode())) {
		serverChannelClass = EpollServerSocketChannel.class;
	}
	else {
		serverChannelClass = NioServerSocketChannel.class;
	}

	bootstrap = bootstrap.group(bossGroup, workerGroup).channel(serverChannelClass);
	bootstrap.option(ChannelOption.TCP_NODELAY, true);

	if (scheduledExecutor != null) {
		bootstrap.handler(scheduledExecutor);
	}

	bootstrap.childHandler(new MqttChannelInitializer(useWebSocket, useSsl));

	bootstrap.childOption(ChannelOption.TCP_NODELAY, true)
			// setting buffer size can improve I/O
			.childOption(ChannelOption.SO_SNDBUF, 1048576).childOption(ChannelOption.SO_RCVBUF, 1048576)
			// recommended in
			// http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#11.0
			.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024))
			.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

	bootstrap.bind(port).sync();
}