Java Code Examples for io.netty.bootstrap.ServerBootstrap

The following are top voted examples for showing how to use io.netty.bootstrap.ServerBootstrap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: elasticsearch_my   File: Netty4Transport.java   Source Code and License 7 votes vote down vote up
@Override
@SuppressForbidden(reason = "debug")
protected void stopInternal() {
    Releasables.close(serverOpenChannels, () -> {
        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 (bootstrap != null) {
            bootstrap.config().group().shutdownGracefully(0, 5, TimeUnit.SECONDS).awaitUninterruptibly();
            bootstrap = null;
        }
    });
}
 
Example 2
Project: tasfe-framework   File: NettyEmbeddedServletContainer.java   Source Code and License 7 votes vote down vote up
@Override
public void start() throws EmbeddedServletContainerException {
    ServerBootstrap b = new ServerBootstrap();
    groups(b);
    servletExecutor = new DefaultEventExecutorGroup(50);
    b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context));

    // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here
    context.setInitialised(true);

    ChannelFuture future = b.bind(address).awaitUninterruptibly();
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable cause = future.cause();
    if (null != cause) {
        throw new EmbeddedServletContainerException("Could not start Netty server", cause);
    }
    logger.info(context.getServerInfo() + " started on port: " + getPort());
}
 
Example 3
Project: simulacron   File: Server.java   Source Code and License 6 votes vote down vote up
Server(
    AddressResolver addressResolver,
    EventLoopGroup eventLoopGroup,
    boolean customEventLoop,
    Timer timer,
    boolean customTimer,
    long bindTimeoutInNanos,
    StubStore stubStore,
    boolean activityLogging,
    ServerBootstrap serverBootstrap) {
  // custom constructor onyl made to help facilitate testing with a custom bootstrap.
  this.addressResolver = addressResolver;
  this.timer = timer;
  this.customTimer = customTimer;
  this.eventLoopGroup = eventLoopGroup;
  this.customEventLoop = customEventLoop;
  this.serverBootstrap = serverBootstrap;
  this.bindTimeoutInNanos = bindTimeoutInNanos;
  this.stubStore = stubStore;
  this.activityLogging = activityLogging;
}
 
Example 4
Project: simulacron   File: Server.java   Source Code and License 6 votes vote down vote up
private Server(
    AddressResolver addressResolver,
    EventLoopGroup eventLoopGroup,
    Class<? extends ServerChannel> channelClass,
    boolean customEventLoop,
    Timer timer,
    boolean customTimer,
    long bindTimeoutInNanos,
    StubStore stubStore,
    boolean activityLogging) {
  this(
      addressResolver,
      eventLoopGroup,
      customEventLoop,
      timer,
      customTimer,
      bindTimeoutInNanos,
      stubStore,
      activityLogging,
      new ServerBootstrap()
          .group(eventLoopGroup)
          .channel(channelClass)
          .childHandler(new Initializer()));
}
 
Example 5
Project: redant   File: SlaveServer.java   Source Code and License 6 votes vote down vote up
public void start(SlaveNode slaveNode) {
    if(slaveNode==null){
        throw new IllegalArgumentException("slaveNode is null");
    }
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 SlaveServerInitializer());

        ChannelFuture future = b.bind(slaveNode.getPort()).sync();
        LOGGER.info("SlaveServer Startup at port:{}",slaveNode.getPort());

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 6
Project: redant   File: NettyServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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());

        ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
        logger.info("NettyServer Startup at port:{}",CommonConstants.SERVER_PORT);

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 7
Project: PetiteRPC   File: NettyAcceptor.java   Source Code and License 6 votes vote down vote up
@Override
public void bind(int port) {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
    EventLoopGroup workerGroup = new NioEventLoopGroup();  
    ServerBootstrap bootstrap = new ServerBootstrap()
            .group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(8888))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new Encoder(serializer), new Decoder(serializer), new ProviderHandler());
                }
                
            });
    
    bootstrap.bind(port);
}
 
Example 8
Project: os   File: TcpChatServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start() throws Exception {
    try {
        ServerBootstrap b = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(serverInitializer);

        logger.info("Starting TcpChatServer... Port: " + port);

        channelFuture = b.bind(port).sync();

    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                shutdown();
            }
        });
    }
}
 
Example 9
Project: os   File: WebSocketChatServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start() throws Exception {
    try {
        ServerBootstrap b = new ServerBootstrap()
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(serverInitializer);

        logger.info("Starting WebSocketChatServer... Port: " + port);

        channelFuture = b.bind(port).sync();
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                shutdown();
            }
        });
    }
}
 
Example 10
Project: upgradeToy   File: SimpleServer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_REUSEADDR, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new SimpleServerHandler());
                    }
                });
        b.bind(8090).sync().channel().closeFuture().sync();
    }
 
Example 11
Project: Limitart   File: AbstractNettyServer.java   Source Code and License 6 votes vote down vote up
protected AbstractNettyServer(String serverName) {
	this.serverName = Objects.requireNonNull(serverName, "server name");
	bootstrap = new ServerBootstrap();
	if (Epoll.isAvailable()) {
		bootstrap.option(ChannelOption.SO_BACKLOG, 1024).channel(EpollServerSocketChannel.class)
				.childOption(ChannelOption.SO_LINGER, 0).childOption(ChannelOption.SO_REUSEADDR, true)
				.childOption(ChannelOption.SO_KEEPALIVE, true);
		log.info(serverName + " epoll init");
	} else {
		bootstrap.channel(NioServerSocketChannel.class);
		log.info(serverName + " nio init");
	}
	bootstrap.group(bossGroup, workerGroup).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
			.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
			.childOption(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					initPipeline(ch.pipeline());
				}
			});
}
 
Example 12
Project: mini-dubbo   File: NettyServer.java   Source Code and License 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 13
Project: ace   File: DefaultServer.java   Source Code and License 6 votes vote down vote up
/**
 * 启动服务
 *
 * @throws Exception 异常
 */
public void start() throws Exception {
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, aceServerConfig.getBackSize())
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        ChannelFuture future = bootstrap.bind(aceServerConfig.getPort()).sync();
        System.out.println("ace server starter on port : " + aceServerConfig.getPort());
        future.channel().closeFuture().sync();
    } finally {
        close();
    }


}
 
Example 14
Project: probe   File: Socks5ProxyServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start(Config config) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    int port = config.getPort();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
                .childHandler(new SocksServerInitializer(config));

        log.info("Socks5 server bind port: {}", port);

        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 15
Project: neoscada   File: Receiver.java   Source Code and License 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 16
Project: message-broker   File: Server.java   Source Code and License 6 votes vote down vote up
private ChannelFuture bindToSslSocket()
        throws InterruptedException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, IOException {
    String hostname = configuration.getHostName();
    int port = Integer.parseInt(configuration.getSsl().getPort());

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
     .channel(NioServerSocketChannel.class)
     .childHandler(new SslSocketChannelInitializer(ioExecutors, new SslHandlerFactory(configuration)))
     .option(ChannelOption.SO_BACKLOG, 128)
     .childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(hostname, port).sync();
    LOGGER.info("Listening AMQP/" + configuration.getSsl().getProtocol() + " on " + hostname + ":" + port);
    return future;
}
 
Example 17
Project: chromium-net-for-android   File: Http2TestServer.java   Source Code and License 6 votes vote down vote up
public void run() {
    try {
        // Configure the server.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new Http2ServerInitializer(mSslCtx));

            sServerChannel = b.bind(PORT).sync().channel();
            Log.i(TAG, "Netty HTTP/2 server started on " + getServerUrl());
            sBlock.open();
            sServerChannel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
        Log.i(TAG, "Stopped Http2TestServerRunnable!");
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
 
Example 18
Project: netty-socketio-demo   File: HttpCheckServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpRequestDecoder());
                        pipeline.addLast(new HttpResponseEncoder());
                        pipeline.addLast(new SimpleServerHandler());
                    }
                });

        ChannelFuture future = bootstrap.bind(port).sync();
        logger.info("Check server started at port: {}", this.port);
    } catch (Exception e) {
        e.printStackTrace();
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        logger.error("Check server start exception", e);
    }
}
 
Example 19
Project: push-server   File: NettyServerBootstrap.java   Source Code and License 6 votes vote down vote up
private void bind() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup(1);
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new NettyServerInitializer());

    ChannelFuture f = bootstrap.bind(port).sync();
    if (f.isSuccess()) {
        logger.info("server start---------------");
    }
}
 
Example 20
Project: jeesupport   File: NettyServer.java   Source Code and License 6 votes vote down vote up
public void start(){
	logger.debug( "--Socket Server will start------------" ) ;
	boss = new NioEventLoopGroup() ;
	work = new NioEventLoopGroup() ;
	int port = CommonConfig.getInteger( SOCKET_PORT1 );
	try {
		
		logger.info( "Netty Server[" + port + "] started..." ) ;
		ServerBootstrap b = new ServerBootstrap() ;

		b.group( boss , work ) ;
		b.channel( NioServerSocketChannel.class ) ;
		b.childHandler( nettyInitializer ) ;
		b.bind( port ).sync().channel().closeFuture().sync() ;
	} catch ( Exception e ) {
		String err_string = e.toString();
		if( err_string.indexOf( "childHandler" ) != -1 ){
			logger.error( "Netty Server[" + port + "] NettyInitializer can't find." ) ;
		}else{
			logger.error( "Netty Server[" + port + "] onload err:" + e.toString() , e  ) ;
		}
	} finally {
		logger.error( "Netty Server[" + port + "] will be unload..."  ) ;
		unload();
	}
}
 
Example 21
Project: cr-private-server   File: NetworkServer.java   Source Code and License 6 votes vote down vote up
public void start() {
	bossGroup = new NioEventLoopGroup();
	workerGroup = new NioEventLoopGroup();

	ServerBootstrap bootstrap = new ServerBootstrap();
	bootstrap
			.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childOption(ChannelOption.SO_KEEPALIVE, true)
			.childHandler(new PlayerInitializer(this));

	try {
		channel = bootstrap.bind(server.getConfig().get("server.port").getAsShort()).sync().channel();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 
Example 22
Project: iothub   File: MqttTransportService.java   Source Code and License 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
  log.info("Setting resource leak detector level to {}", leakDetectorLevel);
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

  log.info("Starting MQTT transport...");
  log.info("Lookup MQTT transport adaptor {}", adaptorName);
  // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName);

  log.info("Starting MQTT transport server");
  bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
  workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true)
      .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
      .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService,
          assetAuthService, relationService, sslHandlerProvider));

  serverChannel = b.bind(host, port).sync().channel();
  log.info("Mqtt transport started: {}:{}!", host, port);
}
 
Example 23
Project: sds   File: NettyServerServiceImpl.java   Source Code and License 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(heartTime,socketService,applicationContext));
        // Bind and start to accept incoming connections.
        b.bind(port);

        logger.info("socket: "+port+" 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 24
Project: netty-socks   File: ServerMain.java   Source Code and License 6 votes vote down vote up
public void start() throws InterruptedException {
    EventLoopGroup acceptors = new NioEventLoopGroup(socksProperties.getAcceptors());
    EventLoopGroup workers = new NioEventLoopGroup();
    EventLoopGroup forwarders = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptors, workers)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, socksProperties.getBacklog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, socksProperties.getConnectTimeoutMillis())
                .childHandler(new Socks5WorkerChannelInitializer(socksProperties, forwarders));

        Address address = socksProperties.getListen();
        ChannelFuture future = bootstrap.bind(address.getHost(), address.getPort()).sync();
        future.channel().closeFuture().sync();
    } finally {
        forwarders.shutdownGracefully();
        workers.shutdownGracefully();
        acceptors.shutdownGracefully();
    }
}
 
Example 25
Project: DecompiledMinecraft   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 26
Project: iotplatform   File: MqttTransportService.java   Source Code and License 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
  log.info("Setting resource leak detector level to {}", leakDetectorLevel);
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

  log.info("Starting MQTT transport...");
  log.info("Lookup MQTT transport adaptor {}", adaptorName);
  // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName);

  log.info("Starting MQTT transport server");
  bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
  workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true)
      .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
      .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService,
          assetAuthService, relationService, sslHandlerProvider));

  serverChannel = b.bind(host, port).sync().channel();
  log.info("Mqtt transport started: {}:{}!", host, port);
}
 
Example 27
Project: ClusterDeviceControlPlatform   File: NettyServer.java   Source Code and License 6 votes vote down vote up
@Override
public void run(String... args) throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(group)
            .channel(NioServerSocketChannel.class)
            .childHandler(serverChannelInitializer);
    ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(30232));
    channelFuture.addListener(future -> {
        if (future.isSuccess()) {
            logger.info("「Netty」服务器启动成功");
        } else {
            logger.info("「Netty」服务器启动失败");
        }
    });
}
 
Example 28
Project: kcp-netty   File: TcpRttServer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new TcpRttDecoder())
                                .addLast(new TcpRttServerHandler());
                    }
                }).childOption(ChannelOption.TCP_NODELAY, true);

        // 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.
        group.shutdownGracefully();
    }
}
 
Example 29
Project: echidna   File: SimpleEchidnaServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start() {
	this.bossGroup = NettyUtils.createEventLoopGroup(1);
	this.workerGroup = NettyUtils.createEventLoopGroup(4);
	
	Class<? extends ServerChannel> serverChannelClass = NettyUtils.getServerChannelClass();
	
	this.logger.info("I am going to start a server on {}:{}.", this.config.getServerHost(),
		this.config.getServerPort());
	
	ServerBootstrap serverBootstrap = new ServerBootstrap();
	try {
		channel = serverBootstrap
			.group(bossGroup, workerGroup)
			.channel(serverChannelClass)
			.childHandler(new ServerChannelInitializer(this))
			.childOption(ChannelOption.SO_KEEPALIVE, true)
			.bind(config.getServerHost(), config.getServerPort())
			.sync().channel();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	this.logger.info("Started the server on {}:{}.", this.config.getServerHost(),
		this.config.getServerPort());
}
 
Example 30
Project: AlphaLibary   File: EchoServer.java   Source Code and License 6 votes vote down vote up
public void start() {
    ServerBootstrap b = new ServerBootstrap();

    b.group(workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    System.out.println("New client connected! (" + socketChannel.localAddress() + ")");

                    socketChannel.pipeline().addLast(new StringEncoder()).addLast(new StringEncoder()).addLast(new EchoServerHandler());
                }
            });

    f = b.bind(port);
}
 
Example 31
Project: Razor   File: NettyServer.java   Source Code and License 6 votes vote down vote up
private void startServer() throws Exception {

        Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(masterGroup, slaveGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpServerInitializer(razor))
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            this.channel = bootstrap.bind(env.get(ENV_KEY_SERVER_HOST, DEFAULT_SERVER_HOST), env.getInt(ENV_KEY_SERVER_PORT, DEFAULT_SERVER_PORT)).sync().channel();
            log.info("{} started and listen on {}", HttpServerHandler.class.getName(), channel.localAddress());
        } catch (final InterruptedException e){

            log.error("Netty server startup failed, error: {}", e.getMessage());
        }
    }
 
Example 32
Project: iot-platform   File: Application.java   Source Code and License 6 votes vote down vote up
public void start(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MqttDecoder());
                        ch.pipeline().addLast(MqttEncoder.INSTANCE);
                        ch.pipeline().addLast(new MqttInBoundHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture future = bootstrap.bind(port).sync();
        future.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
 
Example 33
Project: BaseClient   File: NetworkSystem.java   Source Code and License 6 votes vote down vote up
/**
 * Adds a channel that listens locally
 */
public SocketAddress addLocalEndpoint()
{
    ChannelFuture channelfuture;

    synchronized (this.endpoints)
    {
        channelfuture = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(LocalServerChannel.class)).childHandler(new ChannelInitializer<Channel>()
        {
            protected void initChannel(Channel p_initChannel_1_) throws Exception
            {
                NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.SERVERBOUND);
                networkmanager.setNetHandler(new NetHandlerHandshakeMemory(NetworkSystem.this.mcServer, networkmanager));
                NetworkSystem.this.networkManagers.add(networkmanager);
                p_initChannel_1_.pipeline().addLast((String)"packet_handler", (ChannelHandler)networkmanager);
            }
        }).group((EventLoopGroup)eventLoops.getValue()).localAddress(LocalAddress.ANY)).bind().syncUninterruptibly();
        this.endpoints.add(channelfuture);
    }

    return channelfuture.channel().localAddress();
}
 
Example 34
Project: ss-java   File: ShadowsocksClient.java   Source Code and License 6 votes vote down vote up
public Future startAsync() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new SocksServerInitializer())
             .childAttr(OPTION_ATTRIBUTE_KEY, option);

    return bootstrap.bind(option.getLocalHost(), option.getLocalPort()).addListener(
            new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (infoEnable) {
                        if (future.isSuccess()) {
                            logger.info("Listening on local port {}", option.getLocalPort());
                        } else {
                            logger.info("Shadowsocks client startup failed", future.cause());
                        }
                    }
                }
            });
}
 
Example 35
Project: Ink   File: InkServer.java   Source Code and License 6 votes vote down vote up
public void start() {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpChannelInitializer(list));
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("start listen in port {}", port);
            future.channel().closeFuture().sync();
        } catch (Exception e ) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
 
Example 36
Project: netty_op   File: ErrorTimeServer.java   Source Code and License 6 votes vote down vote up
/**
 *@description 监听指定端口
 *@time 创建时间:2017年7月21日下午3:50:26
 *@param port
 *@throws InterruptedException
 *@author dzn
 */
public void bind(int port) throws InterruptedException{
    //分配任务线程池
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    
    //执行任务线程池
    EventLoopGroup workGroup = new NioEventLoopGroup();
    try{
        //netty Server端
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .childHandler(new ChildChannelHandler());
        
        //启动netty服务器
        ChannelFuture cf = server.bind(port).sync();
        System.out.println("服务器已启动, 监控端口号为 : " + port);
        
        //等待服务器端关闭
        cf.channel().closeFuture().sync();
    }finally{
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
 
Example 37
Project: UnknownPandaServer   File: ConnectionProvider.java   Source Code and License 6 votes vote down vote up
public void start() throws Exception {
    UnknownPandaServer.getLogger().info("Loading protocol");
    Protocol protocol = ProtocolSpecification.getProtocol();
    protocol.load();

    UnknownPandaServer.getLogger().info("Binding UniverseServer at *::" + port + " [tcp]");
    this.channel = new ServerBootstrap()
            .group(Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup())
            .channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            //.childOption(ChannelOption.TCP_NODELAY, true)
            .childHandler(new ConnectionInitializer(this))
            .localAddress("", port)
            .bind()
            .addListeners(this)
            .sync()
            .channel();
}
 
Example 38
Project: sansa   File: SimpleSansaServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start() {
    this.bossGroup = NettyUtils.createEventLoopGroup(1);
    this.workerGroup = NettyUtils.createEventLoopGroup(4);

    Class<? extends ServerChannel> serverChannelClazz = NettyUtils.getServerChannelClass();
    ChannelHandler channelInitializer = new SansaServerChannelInitializer(userManager);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    this.logger.info("Starting a sansa server.");

    try {
        channel = serverBootstrap
                .group(this.bossGroup, this.workerGroup)
                .channel(serverChannelClazz)
                .childHandler(channelInitializer)
                .option(ChannelOption.TCP_NODELAY, true)
                .bind(1100).sync().channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    this.logger.info("Sansa is now rocking the shit.");
}
 
Example 39
Project: happylifeplat-transaction   File: NettyServerServiceImpl.java   Source Code and License 5 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);
      /*  bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup(MAX_THREADS * 2);
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childHandler(nettyServerHandlerInitializer);*/
        b.bind(nettyConfig.getPort());
        LOGGER.info("netty service started on port: " + nettyConfig.getPort());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 40
Project: angel   File: MatrixTransportServer.java   Source Code and License 5 votes vote down vote up
public void start() {
  Configuration conf = context.getConf();
  int workerNum =
      conf.getInt(AngelConf.ANGEL_NETTY_MATRIXTRANSFER_SERVER_EVENTGROUP_THREADNUM,
          AngelConf.DEFAULT_ANGEL_NETTY_MATRIXTRANSFER_SERVER_EVENTGROUP_THREADNUM);

  int sendBuffSize =
      conf.getInt(AngelConf.ANGEL_NETTY_MATRIXTRANSFER_SERVER_SNDBUF,
          AngelConf.DEFAULT_ANGEL_NETTY_MATRIXTRANSFER_SERVER_SNDBUF);

  int recvBuffSize =
      conf.getInt(AngelConf.ANGEL_NETTY_MATRIXTRANSFER_SERVER_RCVBUF,
          AngelConf.DEFAULT_ANGEL_NETTY_MATRIXTRANSFER_SERVER_RCVBUF);

  final int maxMessageSize =
      conf.getInt(AngelConf.ANGEL_NETTY_MATRIXTRANSFER_MAX_MESSAGE_SIZE,
          AngelConf.DEFAULT_ANGEL_NETTY_MATRIXTRANSFER_MAX_MESSAGE_SIZE);

  bossGroup = new NioEventLoopGroup(1);
  workerGroup = new NioEventLoopGroup(workerNum);
  ((NioEventLoopGroup) workerGroup).setIoRatio(70);

  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
      .option(ChannelOption.SO_SNDBUF, sendBuffSize)
      .option(ChannelOption.SO_RCVBUF, recvBuffSize)
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline p = ch.pipeline();
          p.addLast(new LengthFieldBasedFrameDecoder(maxMessageSize, 0, 4, 0, 4));
          p.addLast(new LengthFieldPrepender(4));
          p.addLast(new MatrixTransportServerHandler(context));
        }
      });

  channelFuture = b.bind(port);
}
 
Example 41
Project: angel   File: NettyServer.java   Source Code and License 5 votes vote down vote up
public NettyServer(InetSocketAddress addr, Configuration conf) {
  int nThreads = conf.getInt(AngelConf.SERVER_IO_THREAD, Runtime
      .getRuntime().availableProcessors() * 2);
  IOMode ioMode = IOMode.valueOf(conf.get(AngelConf.NETWORK_IO_MODE, "NIO"));
  EventLoopGroup bossGroup =
      NettyUtils.createEventLoop(ioMode, nThreads,   "ML-server");
  EventLoopGroup workerGroup = bossGroup;
  PooledByteBufAllocator allocator =
      NettyUtils.createPooledByteBufAllocator(true, true, nThreads);
  bootstrap = new ServerBootstrap()
      .group(bossGroup, workerGroup)
      .channel(NettyUtils.getServerChannelClass(ioMode))
      .option(ChannelOption.ALLOCATOR, allocator)
      .childOption(ChannelOption.ALLOCATOR, allocator);
  bootstrap.option(ChannelOption.TCP_NODELAY, true);
  bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
      ch.pipeline()
          .addLast("encoder", NettyFrameEncoder.INSTANCE)
          .addLast("frameDecoder", NettyUtils.createFrameDecoder())
          .addLast("decoder", NettyFrameDecoder.INSTANCE)
          .addLast("handler", new NettyServerMLHandler());
    }
  });
  channelFuture = bootstrap.bind(addr);
  channelFuture.syncUninterruptibly();

  port = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
  LOG.debug("server started on port: {}", port);
  this.addr = addr;
}
 
Example 42
Project: Quavo   File: NetworkExecutor.java   Source Code and License 5 votes vote down vote up
/**
 * Starts the network for a {@link Server}.
 * 
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
	EventLoopGroup boss = new NioEventLoopGroup();
	EventLoopGroup worker = new NioEventLoopGroup();
	ServerBootstrap bootstrap = new ServerBootstrap();

	bootstrap.group(boss, worker);
	bootstrap.channel(NioServerSocketChannel.class);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();

			pipeline.addLast("decoder", new ConnectionDecoder());
			pipeline.addLast("encoder", new ConnectionEncoder());
			pipeline.addLast("adapter", new NetworkMessageHandler());
		}

	});
	bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

	try {
		bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}

	System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address " + Constants.HOST_NAME + ".");
}
 
Example 43
Project: push-network-proxies   File: NotificationRegisterEndpoint.java   Source Code and License 5 votes vote down vote up
protected void startNotificationRegisterEndpoint(final String host, final int port) {

        Runnable notificationRegisterEndpointRunnable = new Runnable() {

            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup(1);
                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 NotificationRegisterServerInitializer());

                    Channel ch = b.bind(host, port).sync().channel();

                    logger.info(String.format("Notification register endpoint started at %s:%s", host, port));

                    ch.closeFuture().sync();
                } catch (InterruptedException ex) {
                    logger.info("Notification register endpoint was interrupted.");
                } finally {
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                }

            }
        };

        notificationEndpointThread = new Thread(notificationRegisterEndpointRunnable);
        notificationEndpointThread.start();
    }
 
Example 44
Project: AgentX   File: XClient.java   Source Code and License 5 votes vote down vote up
public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new SocksInitRequestDecoder())
                                .addLast(new SocksMessageEncoder())
                                .addLast(new Socks5Handler())
                                .addLast(Status.TRAFFIC_HANDLER);
                    }
                });
        log.info("\tStartup {}-{}-client [{}{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getMode(), config.getMode().equals("socks5") ? "" : ":" + config.getProtocol());
        new Thread(() -> new UdpServer().start()).start();
        ChannelFuture future = bootstrap.bind(config.getLocalHost(), config.getLocalPort()).sync();
        future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getLocalHost(), config.getLocalPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 45
Project: AgentX   File: XServer.java   Source Code and License 5 votes vote down vote up
public void start() {
    Configuration config = Configuration.INSTANCE;
    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast("logging", new LoggingHandler(LogLevel.DEBUG))
                                .addLast(new XConnectHandler());
                        if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) {
                            socketChannel.pipeline().addLast(
                                    new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())
                            );
                        }
                    }
                });
        log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol());
        new Thread(() -> new UdpServer().start()).start();
        ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync();
        future.addListener(future1 -> log.info("\tTCP listening at {}:{}...", config.getHost(), config.getPort()));
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        log.error("\tSocket bind failure ({})", e.getMessage());
    } finally {
        log.info("\tShutting down and recycling...");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        Configuration.shutdownRelays();
    }
    System.exit(0);
}
 
Example 46
Project: werewolf_server   File: ThreadServerSocket.java   Source Code and License 5 votes vote down vote up
public void startSocket() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(boss,worker);

        boot.channel(NioServerSocketChannel.class);
        boot.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024*1024,0,4,-4,0,false));
                ch.pipeline().addLast(new ByteToPacketCodec());
                //ch.pipeline().addLast(new LoginChannelHandler(listener));
                ch.pipeline().addLast(new PacketChannelHandler(listener));
            }
        });

        boot.option(ChannelOption.SO_BACKLOG,128);
        boot.childOption(ChannelOption.SO_KEEPALIVE,true);
        channelFuture = boot.bind(port).sync();
        System.out.println("服务器"+port+"开启成功...");
        channelFuture.channel().closeFuture().sync();
    }finally {
        boss.shutdownGracefully().sync();
        worker.shutdownGracefully().sync();
        channelFuture = null;
        System.out.println("服务器关闭成功...");
    }
}
 
Example 47
Project: TakinRPC   File: RemotingNettyServer.java   Source Code and License 5 votes vote down vote up
@Inject
public RemotingNettyServer(final NettyServerConfig serverconfig) {
    bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(serverconfig.getSelectorThreads(), new CustomThreadFactory("boss"));
    //        ExecutorService executor = Executors.newCachedThreadPool();
    workerGroup = new NioEventLoopGroup(serverconfig.getWorkerThreads(), new CustomThreadFactory("worker"));
    respScheduler = new ScheduledThreadPoolExecutor(1);
    this.serverconfig = serverconfig;
}
 
Example 48
Project: TakinRPC   File: RpcServer.java   Source Code and License 5 votes vote down vote up
<T extends ServerSocketChannel> RpcServer(EventLoopGroup eventLoopGroup, EventExecutorGroup eventExecutor, Class<T> channel, SocketAddress address) {
    this.address = address;
    this.allChannels = new DefaultChannelGroup(eventLoopGroup.next());
    this.handler = new ServerHandler(allChannels);
    this.bootstrap = new ServerBootstrap();
    bootstrap.channel(channel);
    bootstrap.childHandler(new ServerInitializer(eventExecutor, handler));
    bootstrap.group(eventLoopGroup);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
}
 
Example 49
Project: proxyee   File: HttpProxyServer.java   Source Code and License 5 votes vote down vote up
public void start(int port) {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
//          .option(ChannelOption.SO_BACKLOG, 100)
//          .handler(new LoggingHandler(LogLevel.DEBUG))
          .childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
              ch.pipeline().addLast("httpCodec", new HttpServerCodec());
              ch.pipeline().addLast("serverHandle",
                  new HttpProxyServerHandle(serverConfig, proxyInterceptInitializer, proxyConfig,
                      httpProxyExceptionHandle));
            }
          });
      ChannelFuture f = b
          .bind(port)
          .sync();
      f.channel().closeFuture().sync();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
 
Example 50
Project: cornerstone   File: HttpHelloWorldServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    //final SslContext sslCtx;
    ConfigurationManager.getConfigInstance().setProperty("app.localLog.path","E:\\Tools\\apache-tomcat-7.0.68\\logs");

    // 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());


        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 51
Project: neto   File: SocketChannelServer.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {

    EventLoopGroup bossGroup = new NioEventLoopGroup(socketServerProperty.getBossThreadCount());
    EventLoopGroup workerGroup = new NioEventLoopGroup(socketServerProperty.getWorkerThreadCount());

    ChannelFuture closeFuture = null;

    try {

        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, SO_BACKLOG)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture bind = b.bind(socketServerProperty.getBindPort());
        ChannelFuture sync = bind.sync();

        sync.addListener(channelServerStartListener);

        Channel ch = sync.channel();
        closeFuture = ch.closeFuture();
        closeFuture.sync();

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 52
Project: skylla   File: SimpleSkyllaServer.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
    this.logger.info("Starting Server.");

    this.bossGroup = NettyUtils.createEventLoopGroup(1);
    this.workerGroup = NettyUtils.createEventLoopGroup(4);

    Class<? extends ServerChannel> serverChannelClazz = NettyUtils.getServerChannelClass();
    ChannelHandler channelInitializer = new SkyllaChannelInitializer(config.getProtocol());

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    try {
        channel = serverBootstrap
                .group(this.bossGroup, this.workerGroup)
                .channel(serverChannelClazz)
                .childHandler(channelInitializer)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_BACKLOG, 50)
                .bind(this.config.getServerHost(), this.config.getServerPort())
                .sync().channel();

        this.logger.info("Server started on {}:{}", this.config.getServerHost(),
                this.config.getServerPort());
    } catch (InterruptedException e) {
        this.logger.error("Server couldnt start, e");
    }
}
 
Example 53
Project: neoscada   File: Server.java   Source Code and License 5 votes vote down vote up
public Server ( final SocketAddress address, final ProtocolOptions options, final List<ServerModule> modules )
{
    this.options = options;

    this.manager = new MessageManager ( this.options );

    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.modules = modules.toArray ( new ServerModule[modules.size ()] );
    for ( final ServerModule module : modules )
    {
        module.initializeServer ( this, this.manager );
    }

    this.channel = this.bootstrap.bind ( address ).channel ();
}
 
Example 54
Project: push   File: MgsServer.java   Source Code and License 5 votes vote down vote up
public void run() {
	ServerBootstrap b = new ServerBootstrap();// 引导辅助程序

	bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
	workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
	try {
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);// 设置nio类型的channel
		b.childHandler(new ChannelInitializer<SocketChannel>() {// 有连接到达时会创建一个channel
			protected void initChannel(SocketChannel ch) throws Exception {
				logger.debug("客户端:{} 初始化", ch.remoteAddress());
				// pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务
				ch.pipeline().addLast("frameDecoder",
						new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
				ch.pipeline().addLast("decoder", msgPackDecode);
				ch.pipeline().addLast("encoder", msgPackEncode);
				ch.pipeline().addLast(serverHandler);
			}
		});
		b.option(ChannelOption.SO_BACKLOG, 128);
		b.childOption(ChannelOption.SO_KEEPALIVE, true);
		logger.info("server start : {}", port);
		ChannelFuture f = b.bind(port).sync();// 配置完成,开始绑定server,通过调用sync同步方法阻塞直到绑定成功
		channel = f.channel();
		f.channel().closeFuture().sync();// 应用程序会一直等待,直到channel关闭
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 55
Project: MooProject   File: NetworkServer.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the server up, that means it initialises the event group and the {@link ServerBootstrap}<br>
 * It adds different de- and encoder to the pipeline to handle packets<br>
 * <p>
 * On Unix systems Epoll is a pretty nice thing, so if this program runs on a Unix system
 * it'll use the {@link EpollEventLoopGroup} and the {@link EpollServerSocketChannel} instead of the default ones
 */
@Override
public NetworkServer setup() {
    this.eventExecutors = PipelineUtil.getEventLoopGroup();

    this.bootstrap = new ServerBootstrap()
            .group(eventExecutors)
            .channel(PipelineUtil.getServerChannel())
            .childHandler(PipelineUtil.getChannelInitializer(this, Protocol.PROTOCOL_VERSION));
    return this;
}
 
Example 56
Project: GoPush   File: NodeServerBootstrap.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void start() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));
                    pipeline.addLast("handler", nodeChannelInBoundHandler);
                }
            })
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_SNDBUF, 2048)
            .option(ChannelOption.SO_RCVBUF, 1024);
    bootstrap.bind(goPushNodeServerConfig.getNodePort()).sync();
    log.info("Node server start successful! listening port: {}", goPushNodeServerConfig.getNodePort());
}
 
Example 57
Project: nettyRpc   File: RpcServer.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化
 *
 * @throws Exception
 */
public void startServer(int port) throws Exception {
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler())
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new RequestWrapperCodec())
                                .addLast(new ResponseWrapperCodec())
                                .addLast(new BusinessServerHandler());
                    }
                });
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        channelFuture.addListener((future) -> System.out.println("server listening at: " + ((ChannelFuture) future).channel()));
        channelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
 
Example 58
Project: hekate   File: NettyServer.java   Source Code and License 5 votes vote down vote up
private <O> void setChildUserOpt(ServerBootstrap boot, ChannelOption<O> opt, O value) {
    if (value != null) {
        if (DEBUG) {
            log.debug("Setting option {} = {} [address={}]", opt, value, address);
        }

        boot.childOption(opt, value);
    }
}
 
Example 59
Project: hekate   File: NettyServer.java   Source Code and License 5 votes vote down vote up
private <O> void setUserOpt(ServerBootstrap boot, ChannelOption<O> opt, O value) {
    if (value != null) {
        if (DEBUG) {
            log.debug("Setting option {} = {} [address={}]", opt, value, address);
        }

        boot.option(opt, value);
    }
}
 
Example 60
Project: jfast   File: NettyTcpServer.java   Source Code and License 5 votes vote down vote up
@Override
public void start() throws Exception {
	if(Objects.isNull(messageConsumer)) {
		throw new IllegalStateException("You must define MessageConsumer!");
	}
	
	this.port = (this.port > 0 ? this.port : DEFAULT_PORT);
	this.maxFrameBuffer = (maxFrameBuffer > 0 ? maxFrameBuffer : DEFAULT_MAX_FAMEBUFFER);
	ServerBootstrap bootstrap = configure();
	
	channel = bootstrap.bind(this.port).channel();
	log.info("NettyTcpServer started on Port {}. With Max Frame Buffer {}", port, this.maxFrameBuffer);
	started.incrementAndGet();
}