Java Code Examples for io.netty.channel.socket.nio.NioServerSocketChannel

The following are top voted examples for showing how to use io.netty.channel.socket.nio.NioServerSocketChannel. 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: webapp-tyust   File: NettyServer.java   Source Code and License 9 votes vote down vote up
private NettyServer(){
	pGroup = new NioEventLoopGroup();
	cGroup = new NioEventLoopGroup();
	serverBootstrap = new ServerBootstrap();
	serverBootstrap.group(pGroup, cGroup)
	 .channel(NioServerSocketChannel.class)
	 .option(ChannelOption.SO_BACKLOG, 1024)
	 //设置日志
	 .handler(new LoggingHandler(LogLevel.INFO))
	 .childHandler(new ChannelInitializer<SocketChannel>() {
		protected void initChannel(SocketChannel sc) throws Exception {
			sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
			sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
			sc.pipeline().addLast(new ReadTimeoutHandler(60));
			sc.pipeline().addLast(new NettyServerHandler());
		}
	});		
}
 
Example 2
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 3
Project: redant   File: MasterServer.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 MasterServerInitializer());

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

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
Project: miracle-remote   File: NettyServer.java   Source Code and License 6 votes vote down vote up
@Override
public void start(final int port) {
    bossGroup = new NioEventLoopGroup(bossGroupThreads);
    workerGroup = new NioEventLoopGroup(workerGroupThreads);
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    try {
    serverBootstrap
        .group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, backlogSize)
        .childOption(ChannelOption.SO_KEEPALIVE, true)
        .childOption(ChannelOption.TCP_NODELAY, true)
        .childHandler(serializeType.getServerChannelInitializer().newInstance());
        channel = serverBootstrap.bind(port).sync().channel();
    } catch (final Exception ex) {
        throw new ServerException(Server.SYSTEM_MESSAGE_ID, ex);
    }
}
 
Example 11
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 12
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 13
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 14
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 15
Project: message-broker   File: Server.java   Source Code and License 6 votes vote down vote up
private ChannelFuture bindToPlainSocket() throws InterruptedException {
    String hostname = configuration.getHostName();
    int port = Integer.parseInt(configuration.getPlain().getPort());

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new SocketChannelInitializer(ioExecutors))
            .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 on " + hostname + ":" + port);
    return future;
}
 
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: 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 19
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 20
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 21
Project: mapsforge-web   File: HttpServer.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	EventLoopGroup bossGroup = new NioEventLoopGroup();
       EventLoopGroup workerGroup = new NioEventLoopGroup();
       
       try{
           ServerBootstrap serverBootstrap = new ServerBootstrap();
           serverBootstrap.group(bossGroup,workerGroup)
           		.channel(NioServerSocketChannel.class)
           		.childHandler(new HttpServer());
           ChannelFuture channelFuture = serverBootstrap
           		.bind(new InetSocketAddress("0.0.0.0", PORT))
           		.sync();
           channelFuture.channel().closeFuture().sync();
       } finally {
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
       }
}
 
Example 22
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 23
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 24
Project: DovakinMQ   File: DovakinMQServer.java   Source Code and License 6 votes vote down vote up
public void start(){
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(workerGroup,bossGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new TCPHandlerInitializer(this))
            .option(ChannelOption.SO_BACKLOG, 512)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    Channel serverChannel = bootstrap.bind(new InetSocketAddress(port)).channel();
    ChannelFuture future = serverChannel.closeFuture();
    try {
        System.out.println("MQTT服务器已启动...");
        future.sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 25
Project: DistributedID   File: SdkServer.java   Source Code and License 6 votes vote down vote up
@Override
public void init() {
    super.init();
    b.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defLoopGroup,
                            new SdkServerDecoder(12),  // 自定义解码器
                            new SdkServerEncoder(),    // 自定义编码器
                            new SdkServerHandler(snowFlake) // 自定义处理器
                    );
                }
            });
}
 
Example 26
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 27
Project: netty_op   File: RightTimeServer.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{
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .childHandler(new ChildChannelHandler());
        ChannelFuture cf = server.bind(port).sync();
        System.out.println("服务器已启动, 监控端口号为 : " + port);
        cf.channel().closeFuture().sync();
    }finally{
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
 
Example 28
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 29
Project: netty_op   File: TimeServer.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{
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .childHandler(new ChildChannelHandler());
        ChannelFuture cf = server.bind(port).sync();
        System.out.println("服务器已启动, 监控端口号为 : " + port);
        cf.channel().closeFuture().sync();
    }finally{
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
 
Example 30
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 31
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 32
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 33
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 34
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 35
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 36
Project: rpc-thunderdome   File: GrpcServer.java   Source Code and License 5 votes vote down vote up
public static void main(String... args) throws Exception {
  System.out.println("starting server");

  String host = System.getProperty("host", "0.0.0.0");
  int port = Integer.getInteger("port", 8001);
  boolean useEpoll = Boolean.getBoolean("usePoll");

  Class channel;
  
  if (useEpoll) {
    channel = EpollServerSocketChannel.class;
  } else  {
    channel = NioServerSocketChannel.class;
  }

  ThreadFactory tf = new DefaultThreadFactory("server-elg-", true /*daemon */);
  NioEventLoopGroup boss = new NioEventLoopGroup(1, tf);
  NioEventLoopGroup worker = new NioEventLoopGroup(0, tf);
  NettyServerBuilder builder =
      NettyServerBuilder.forPort(port)
          .bossEventLoopGroup(boss)
          .workerEventLoopGroup(worker)
          .channelType(channel)
          .addService(new DefaultService())
          .directExecutor()
          .maxConcurrentCallsPerConnection(Runtime.getRuntime().availableProcessors() * 256)
          .flowControlWindow(NettyChannelBuilder.DEFAULT_FLOW_CONTROL_WINDOW * 10);

  io.grpc.Server start = builder.build();
  start.start();

  System.out.println("server started");
  start.awaitTermination();
}
 
Example 37
Project: monica   File: SocketServer.java   Source Code and License 5 votes vote down vote up
public void start() throws Exception {
	// Configure SSL.
	final SslContext sslCtx;
	if (SSL) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
	} else {
		sslCtx = null;
	}

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

		// Start the server.
		ChannelFuture f = b.bind(getHostAddress(), PORT).sync();
		// System.out.println("server is started "+f.isSuccess());
		setStarted(true);
		// Wait until the server socket is closed.
		f.channel().closeFuture().sync();
	} finally {
		// Shut down all event loops to terminate all threads.
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

}
 
Example 38
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 39
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 40
Project: TakinRPC   File: RemotingNettyServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void doStart() {
    try {
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
        bootstrap.localAddress(serverconfig.getListenPort());
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws IOException {

                ch.pipeline().addLast("idleState", new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                ch.pipeline().addLast("heartbeat", new HeartbeatHandler());
                ch.pipeline().addLast(new KyroMsgDecoder());
                ch.pipeline().addLast(new KyroMsgEncoder());
                ch.pipeline().addLast("invoker", new NettyServerHandler());
            }
        });

        ChannelFuture channelFuture = this.bootstrap.bind().sync();
        //        channelFuture.channel().closeFuture().sync();
        logger.info("server started on port:" + serverconfig.getListenPort());
        respScheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                scanResponseTable(5000);
            }
        }, 60 * 1000, 60 * 1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        logger.error("", e);
        System.exit(-1);
    }
}
 
Example 41
Project: uavstack   File: AbstractHttpServiceComponent2.java   Source Code and License 5 votes vote down vote up
@Override
public void start(int port, int backlog, int listenThreadCount, int handleThreadCount, boolean forceExit) {

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

    server = new ServerBootstrap();
    server.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(port)
            .option(ChannelOption.SO_BACKLOG, backlog).childHandler(new HttpServerInitializer(this));

    try {
        this.host = NetworkHelper.getLocalIP();
        this.port = port;

        // Start the server.
        server.bind().sync();

        if (log.isTraceEnable()) {
            log.info(this, "HttpServiceComponent[" + this.cName + "] for feature[" + this.feature
                    + "] started SUCCESS: port=" + this.port);
        }
    }
    catch (InterruptedException e) {
        log.err(this, "HttpServiceComponent[" + this.cName + "] for feature[" + this.feature + "] starts FAIL.", e);

        if (forceExit == true) {
            System.exit(-1);
        }

    }
}
 
Example 42
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 43
Project: tx-lcn   File: NettyServerServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
    int heartTime = transaction_netty_heart_time+10;
    txCoreServerHandler = new TxCoreServerHandler(mqTxManagerService);
    bossGroup = new NioEventLoopGroup(50); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS));

                        ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                        ch.pipeline().addLast(txCoreServerHandler);
                    }
                });

        // Start the server.
        b.bind(Constants.socketPort);
        logger.info("Socket started on port(s): " + Constants.socketPort + " (socket)");

    } catch (Exception e) {
        // Shut down all event loops to terminate all threads.
        e.printStackTrace();
    }
}
 
Example 44
Project: rpc   File: AbstractServer.java   Source Code and License 5 votes vote down vote up
public AbstractServer(ServerConfig config, int port) throws InterruptedException {
    this.port = port;
    this.config = config;
    serverStateRef = new AtomicReference<>(AbstractServer.ServerState.Created);
    boss = new NioEventLoopGroup();
    worker = new NioEventLoopGroup();
    bootstrap = new ServerBootstrap();

    bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, config.getSoBacklog())
            .option(ChannelOption.SO_KEEPALIVE, config.getSoKeepAlive())
            .option(ChannelOption.TCP_NODELAY, config.getTcpNoDelay())
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(newChannelInitializer());
}
 
Example 45
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 46
Project: GoPush   File: DeviceServerBootstrap.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("logHandler", new LoggingHandler());
                    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", deviceChannelInboundHandler);
                }
            })

            .option(ChannelOption.SO_BACKLOG, 1000000)  //连接队列深度
            .option(ChannelOption.TCP_NODELAY, true)   //设置 no_delay
            .option(ChannelOption.SO_SNDBUF, 2048).option(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_SNDBUF, 2048).childOption(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.SO_LINGER, 0);

    bootstrap.bind(goPushNodeServerConfig.getDevicePort()).sync();
    log.info("device server start successful! listening port: {}", goPushNodeServerConfig.getDevicePort());
}
 
Example 47
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 48
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 49
Project: NSS   File: SocksServer.java   Source Code and License 5 votes vote down vote up
public void start() {
	try {

		FSClient.start();

		Config config = ConfigXmlLoader.load(CONFIG);
		PacLoader.load(PAC);

		bossGroup = new NioEventLoopGroup(1);
		workerGroup = new NioEventLoopGroup();
		bootstrap = new ServerBootstrap();
		trafficHandler = new GlobalTrafficShapingHandler(
				Executors.newScheduledThreadPool(2), 1000);

		bootstrap
				.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(
						new SocksServerInitializer(config, trafficHandler));

		logger.info("Start At Port " + config.get_localPort());
		startMBean();
		bootstrap.bind(config.get_localPort()).sync().channel()
				.closeFuture().sync();
	} catch (Exception e) {
		logger.error("start error", e);
	} finally {
		stop();
	}
}
 
Example 50
Project: rskj   File: JsonRpcNettyServer.java   Source Code and License 5 votes vote down vote up
public void start() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_LINGER, socketLinger);
    b.option(ChannelOption.SO_REUSEADDR, reuseAddress);
    b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpRequestDecoder());
                p.addLast(new HttpObjectAggregator(1024 * 1024 * 5));
                p.addLast(new HttpResponseEncoder());
                p.addLast(new HttpContentCompressor());
                if (corsConfiguration.hasHeader()) {
                    p.addLast(new CorsHandler(
                        CorsConfig
                            .withOrigin(corsConfiguration.getHeader())
                            .allowedRequestHeaders(HttpHeaders.Names.CONTENT_TYPE)
                            .allowedRequestMethods(HttpMethod.POST)
                        .build())
                    );
                }
                p.addLast(jsonRpcWeb3FilterHandler);
                p.addLast(jsonRpcWeb3ServerHandler);
            }
        });
    b.bind(host, port).sync();
}
 
Example 51
Project: rskj   File: PeerServerImpl.java   Source Code and License 5 votes vote down vote up
public void start(int port) {
    // TODO review listening use
    listening = true;

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

    EthereumChannelInitializer ethereumChannelInitializer = ethereumChannelInitializerFactory.newInstance("");

    ethereumListener.trace("Listening on port " + port);


    try {
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);

        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());

        b.handler(new LoggingHandler());
        b.childHandler(ethereumChannelInitializer);

        // Start the client.
        logger.info("Listening for incoming connections, port: [{}] ", port);
        logger.info("NodeId: [{}] ", Hex.toHexString(config.nodeId()));

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

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
        logger.debug("Connection is closed");

        // TODO review listening use
        listening = false;
    } catch (Exception e) {
        logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
        throw new Error("Server Disconnected");
    } finally {
        workerGroup.shutdownGracefully();

    }
}
 
Example 52
Project: ClusterDeviceControlPlatform   File: NettyServer.java   Source Code and License 5 votes vote down vote up
@Override
public void start() {
    new Thread(() -> {
        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 -> startListenerHandle(future, launchListener));
    }).start();
}
 
Example 53
Project: dremio-oss   File: TransportCheck.java   Source Code and License 5 votes vote down vote up
public static Class<? extends ServerSocketChannel> getServerSocketChannel(){
  if(SUPPORTS_EPOLL){
    return EpollServerSocketChannel.class;
  }else{
    return NioServerSocketChannel.class;
  }
}
 
Example 54
Project: sds   File: NettyServerServiceImpl.java   Source Code and License 5 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) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new ByteArrayEncoder());

                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                        ch.pipeline().addLast(new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS));

                        ch.pipeline().addLast(new DeliveryHandler(deliveryService));

                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        b.bind(settingService.getDeliveryPort());

        logger.info("socket: "+settingService.getDeliveryPort()+" 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 55
Project: netty-connection-pool   File: NioConnDroppingServer.java   Source Code and License 5 votes vote down vote up
public NioConnDroppingServer(final int port, final int dropEveryRequest)
throws InterruptedException {
	dispatchGroup = new NioEventLoopGroup();
	workerGroup = new NioEventLoopGroup();
	final ServerBootstrap bootstrap = new ServerBootstrap()
		.group(dispatchGroup, workerGroup)
		.channel(NioServerSocketChannel.class)
		.childHandler(
			new ChannelInitializer<SocketChannel>() {
				@Override
				public final void initChannel(final SocketChannel ch) {
					ch.pipeline().addLast(
						new SimpleChannelInboundHandler<Object>() {
							@Override
							protected final void channelRead0(
								final ChannelHandlerContext ctx, final Object msg
							) throws Exception {
								if(0 == reqCounter.incrementAndGet() % dropEveryRequest) {
									final Channel conn = ctx.channel();
									System.out.println("Dropping the connection " + conn);
									conn.close();
								}
							}
						}
					);
				}
			}
		);

	bindFuture = bootstrap.bind(port).sync();
}
 
Example 56
Project: netty_op   File: NettyHttpFileServer.java   Source Code and License 5 votes vote down vote up
public void run(final int port, final String url) throws Exception{
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workGroup)
              .channel(NioServerSocketChannel.class)
              .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //增加HTTP请求消息解码器
                    ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                    
                    //将多个HTTP消息转换成多个单一的FullHttpRequest或者FullHttpResponse
                    ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
                    
                    //增加Http响应消息编码器
                    ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                    
                    //支持异步发送大码流
                    ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                    
                    //增加文件服务器的业务处理器
                    ch.pipeline().addLast("fileServerHandler", new NettyHttpFileServerHandler(url));
                }
              });
        ChannelFuture future = server.bind(port).sync();
        future.channel().closeFuture().sync();
    }finally{
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
 
Example 57
Project: QDrill   File: TransportCheck.java   Source Code and License 5 votes vote down vote up
public static Class<? extends ServerSocketChannel> getServerSocketChannel(){
  if(SUPPORTS_EPOLL){
    return EpollServerSocketChannel.class;
  }else{
    return NioServerSocketChannel.class;
  }
}
 
Example 58
Project: L2J-Global   File: NetworkManager.java   Source Code and License 5 votes vote down vote up
public NetworkManager(EventLoopGroup bossGroup, EventLoopGroup workerGroup, ChannelInitializer<SocketChannel> clientInitializer, String host, int port)
{
	// @formatter:off
	_serverBootstrap = new ServerBootstrap()
		.group(bossGroup, workerGroup)
		.channel(NioServerSocketChannel.class)
		.childHandler(clientInitializer)
		.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
	// @formatter:on
	_host = host;
	_port = port;
}
 
Example 59
Project: candlelight   File: NetworkEngine.java   Source Code and License 5 votes vote down vote up
public void addPublicEndpoint(InetAddress address, int port)
{
	synchronized (this.endpoints)
	{
		final EventLoopGroup boss = new NioEventLoopGroup();
		final EventLoopGroup worker = new NioEventLoopGroup();
		final ServerBootstrap b = new ServerBootstrap()
				.group(boss, worker)
				.childHandler(new ChannelInitializer<Channel>() {
					@Override
					protected void initChannel(Channel ch) throws Exception
					{
						final PacketRegistry registry = NetworkEngine.this.packetRegistry;
						final NetworkDispatcher dispatch = new NetworkDispatcher(
								NetworkEngine.this, NetworkSide.SERVER);
						NetworkEngine.this.dispatchers.add(dispatch);

						ch.pipeline()
								.addLast(new VarInt21FrameDecoder())
								.addLast(new PacketDecoder(NetworkSide.SERVER, registry))
								.addLast(new VarInt21FrameEncoder())
								.addLast(new PacketEncoder(NetworkSide.CLIENT, registry))
								.addLast(dispatch);
					}
				})
				.channel(NioServerSocketChannel.class);

		//Host and wait until done
		b.localAddress(address, port).bind().syncUninterruptibly();
	}
}
 
Example 60
Project: candlelight   File: Server.java   Source Code and License 5 votes vote down vote up
@Override
public void run()
{
	System.out.println("Starting Server...");
	EventLoopGroup boss = new NioEventLoopGroup();
	EventLoopGroup worker = new NioEventLoopGroup();
	try
	{
		ServerBootstrap b = new ServerBootstrap();
		b.group(boss, worker)
				.channel(NioServerSocketChannel.class)
				.childHandler(new ServerChannelInitializer());

		System.out.println("Connecting...");
		Channel ch = b.bind(ChubbyCat.PORT).sync().channel();
		System.out.println("Connection Established!");

		//Process stuff

		ch.closeFuture().sync();
	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
	finally
	{
		System.out.println("Stopping Server...");
		boss.shutdownGracefully();
		worker.shutdownGracefully();
	}

	System.out.println("Connection Ended!");
}