io.netty.bootstrap.ServerBootstrap Java Examples

The following examples show how to use io.netty.bootstrap.ServerBootstrap. 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 File: EpollSocketTestPermutation.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: QueryServer.java    From incubator-pinot with 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 #3
Source File: NettyServerServiceImpl.java    From Lottor with 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 #4
Source File: CarbonServer.java    From disthene with 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 #5
Source File: TcpServer.java    From krpc with 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 #6
Source File: NettyServerServiceImpl.java    From sds with 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 #7
Source File: EchoServer.java    From Lottor with 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 #8
Source File: SelfCheckHttpServer.java    From krpc with 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 #9
Source File: TelnetServer.java    From netty.book.kor with 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 #10
Source File: CustomService.java    From netty-learning with 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 #11
Source File: DiscardServer.java    From netty.book.kor with 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 #12
Source File: Receiver.java    From neoscada with 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 #13
Source File: EchoServer.java    From yuzhouwan with 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 #14
Source File: Server.java    From xraft with 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 #15
Source File: NettySocketServer.java    From jforgame with 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 #16
Source File: NettyMessagingService.java    From atomix with 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 #17
Source File: NettyRestServer.java    From netty-restful-server with 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 #18
Source File: BootstrapTemplate.java    From netty-cookbook with 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 #19
Source File: ProtocolViolationTests.java    From netty-zmtp with 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 #20
Source File: HttpServer.java    From smartacus-mqtt-broker with 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 #21
Source File: TCPServer.java    From momo-cloud-permission with 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 #22
Source File: NettyServer.java    From mini-dubbo with 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 #23
Source File: GraphiteListener.java    From newts with 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 #24
Source File: NettyServerDemo3.java    From java-study with 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 #25
Source File: Netty4Transport.java    From crate with 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 #26
Source File: NettyNioServer.java    From code with Apache License 2.0 5 votes vote down vote up
public void server(int port) throws Exception {
    final ByteBuf buf =
            Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n",
                    StandardCharsets.UTF_8));
    //为非阻塞模式使用NioEventLoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        //创建ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group).channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                //指定 ChannelInitializer,对于每个已接受的连接都调用它
                .childHandler(new ChannelInitializer<SocketChannel>() {
                                  @Override
                                  public void initChannel(SocketChannel ch)
                                          throws Exception {
                                      ch.pipeline().addLast(
                                              //添加 ChannelInboundHandlerAdapter以接收和处理事件
                                              new ChannelInboundHandlerAdapter() {
                                                  @Override
                                                  public void channelActive(
                                                          //将消息写到客户端,并添加ChannelFutureListener,
                                                          //以便消息一被写完就关闭连接
                                                          ChannelHandlerContext ctx) throws Exception {
                                                      ctx.writeAndFlush(buf.duplicate())
                                                              .addListener(
                                                                      ChannelFutureListener.CLOSE);
                                                  }
                                              });
                                  }
                              }
                );
        //绑定服务器以接受连接
        ChannelFuture f = b.bind().sync();
        f.channel().closeFuture().sync();
    } finally {
        //释放所有的资源
        group.shutdownGracefully().sync();
    }
}
 
Example #27
Source File: NettyServer.java    From nuls-v2 with MIT License 5 votes vote down vote up
public void init() {
    boss = new NioEventLoopGroup(1);
    worker = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.SO_SNDBUF, 128 * 1024)
            .childOption(ChannelOption.SO_RCVBUF, 128 * 1024)
            .childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new NulsChannelInitializer<>(new ServerChannelHandler()));
}
 
Example #28
Source File: DiscardServer.java    From codes-scratch-zookeeper-netty with Apache License 2.0 5 votes vote down vote up
public void run()
        throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    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 DiscardServerHandler());
                    }
                }).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 #29
Source File: ServerApplication.java    From jt808 with Apache License 2.0 5 votes vote down vote up
private void bind() throws Exception {
	this.bossGroup = new NioEventLoopGroup();
	this.workerGroup = new NioEventLoopGroup();
	try {
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class) 
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
						//1024表示单条消息的最大长度,解码器在查找分隔符的时候,达到该长度还没找到的话会抛异常
						ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, true, Unpooled.copiedBuffer(new byte[] { 0x7e }),
								Unpooled.copiedBuffer(new byte[] { 0x7e, 0x7e })));
						//添加业务处理handler
						ch.pipeline().addLast(new ServerHandler());
					}
				}).option(ChannelOption.SO_BACKLOG, 128)
				.childOption(ChannelOption.SO_KEEPALIVE, true);
		LOGGER.info(this.getName() + "启动完毕, 端口={}", this.port);
		ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
		channelFuture.channel().closeFuture().sync();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
           this.workerGroup.shutdownGracefully();
           this.bossGroup.shutdownGracefully();
	}
}
 
Example #30
Source File: BootKit.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 创建bootstrap
 *
 * @param boss 连接线程数
 * @param work 工作线程数
 */
void createServerBootstrap(int boss, int work) {
    bootstrap = new ServerBootstrap();
    if (epollIsAvailable()) {
        createEpollGroup(boss, work);
    } else {
        createNioGroup(boss, work);
    }

    bootstrap.option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

}