Java Code Examples for io.netty.bootstrap.ServerBootstrap#handler()

The following examples show how to use io.netty.bootstrap.ServerBootstrap#handler() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GraphiteListener.java    From newts with Apache License 2.0 6 votes vote down vote up
public void run() {
    try {
        ServerBootstrap bStrap = new ServerBootstrap();
        bStrap.group(m_bossGroup, m_workerGroup);
        bStrap.channel(NioServerSocketChannel.class);
        bStrap.handler(new LoggingHandler(LogLevel.INFO));
        bStrap.childHandler(m_initializer);
        Channel ch = bStrap.bind(this.m_listen).sync().channel();

        ch.closeFuture().sync();
    }
    catch (InterruptedException e) {
        LOG.info("Interrupted; Shutting down!");
    }
    finally {
        m_bossGroup.shutdownGracefully();
        m_workerGroup.shutdownGracefully();
    }
}
 
Example 2
Source File: MixServer.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
private void acceptConnections(@Nonnull MixServerInitializer initializer, int port,
        @Nonnegative int numWorkers) throws InterruptedException {
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup(numWorkers);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(initializer);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();
        this.state = ServerState.RUNNING;

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        this.state = ServerState.STOPPING;
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example 3
Source File: HttpUploadServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 4
Source File: TelnetTelService.java    From hasor with Apache License 2.0 5 votes vote down vote up
@Override
protected void doInitialize() {
    super.doInitialize();
    //
    // .初始化常量配置
    this.workerGroup = new NioEventLoopGroup(1, new NameThreadFactory("tConsole", this.classLoader));
    logger.info("tConsole -> starting... at {}", this.bindAddress);
    //
    // .启动Telnet
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(this.workerGroup, this.workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Unpooled.wrappedBuffer(new byte[] { '\n' })));
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(nettyHandler);
            }
        });
        this.telnetChannel = b.bind(this.bindAddress).sync().channel();
    } catch (Throwable e) {
        logger.error("tConsole -> start failed, " + e.getMessage(), e);
        this.close();
    }
    logger.info("tConsole -> - bindSocket at {}", this.bindAddress);
}
 
Example 5
Source File: HttpUploadServer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 6
Source File: MqttServer.java    From lannister with Apache License 2.0 5 votes vote down vote up
private void executeBootstrap(ScheduledExecutor scheduledExecutor, int port, boolean useWebSocket, boolean useSsl)
		throws InterruptedException {
	ServerBootstrap bootstrap = new ServerBootstrap();

	Class<? extends ServerChannel> serverChannelClass;

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

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

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

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

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

	bootstrap.bind(port).sync();
}
 
Example 7
Source File: HttpServer.java    From ServerCore with Apache License 2.0 5 votes vote down vote up
public void createNetWork() {

        bossGroup = new NioEventLoopGroup(bossThreadCount);
        workerGroup = new NioEventLoopGroup(workThreadCount);

        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_RCVBUF, 128 * 1024);
        bootstrap.childOption(ChannelOption.SO_SNDBUF, 128 * 1024);


        bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline pip = ch.pipeline();
                pip.addLast("codec", new HttpServerCodec());
                pip.addLast("aggregator", new HttpObjectAggregator(512 * 1024));
                pip.addLast("responseEncoder", new ResponseEncoder());
                pip.addLast("requestDecoder", new RequestDecoder());
                pip.addLast("requestHandler", new HttpHandler());

            }
        });
    }
 
Example 8
Source File: NetworkServiceImpl.java    From ServerCore with Apache License 2.0 5 votes vote down vote up
NetworkServiceImpl(final NetworkServiceBuilder builder) {
    int bossLoopGroupCount = builder.getBossLoopGroupCount();
    int workerLoopGroupCount = builder.getWorkerLoopGroupCount();
    this.port = builder.getPort();
    final SslContext sslCtx;

    bossGroup = new NioEventLoopGroup(bossLoopGroupCount);
    workerGroup = new NioEventLoopGroup(workerLoopGroupCount);

    if (builder.isSsl()) {
        try {
            File keyCertChainFile = new File(builder.getSslKeyCertChainFile());
            File keyFile = new File(builder.getSslKeyFile());
            sslCtx = SslContext.newServerContext(keyCertChainFile, keyFile);
        } catch (Exception var4) {
            throw new RuntimeException("sslCtx create failed.", var4);
        }
    } else {
        sslCtx = null;
    }
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_RCVBUF, 128 * 1024);
    bootstrap.childOption(ChannelOption.SO_SNDBUF, 128 * 1024);

    bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));
    if (builder.isWebSocket()) {
        bootstrap.childHandler(new WebSocketHandler(builder, sslCtx));
    } else {
        bootstrap.childHandler(new SocketHandler(builder));
    }
}
 
Example 9
Source File: HttpUploadServer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

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

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

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example 10
Source File: PeerServer.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void start(int port) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(args.getTcpNettyWorkThreadNum());
        GSCChannelInitializer GSCChannelInitializer = ctx.getBean(GSCChannelInitializer.class, "");

        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, this.args.getNodeConnectionTimeout());

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

            // Start the client.
            logger.info("TCP listener started, bind port {}", port);

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

            listening = true;

            // Wait until the connection is closed.
            channelFuture.channel().closeFuture().sync();

            logger.info("TCP listener is closed");

        } catch (Exception e) {
            logger.error("Start TCP server failed.", e);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            listening = false;
        }
    }
 
Example 11
Source File: JT809Server.java    From jt809-tcp-server with MIT License 5 votes vote down vote up
/**
 * 主链路(服务端)引导入口
 * @throws Exception
 */
public void runServer() throws Exception{
    //创建主线程池(接收线程池)
    EventLoopGroup boosGroup = new NioEventLoopGroup(serverConfig.getBossMaxThreadCount(),new DefaultThreadFactory("boosServer",true));
    //创建工作线程池
    EventLoopGroup workGroup = new NioEventLoopGroup(serverConfig.getWorkMaxThreadCount(),new DefaultThreadFactory("workServer",true));

    try {
        //创建一个服务器端的程序类进行NIO的启动,同时可以设置Channel
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //设置要使用的线程池以及当前的Channel 的类型
        serverBootstrap.group(boosGroup,workGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
        //接收到的信息处理器
        serverBootstrap.childHandler(JT809ServerChannelInit);
        serverBootstrap.option(ChannelOption.SO_BACKLOG,128);
        serverBootstrap.option(ChannelOption.TCP_NODELAY, true);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        //ChannelFuture描述异步回调的处理操作
        ChannelFuture future = serverBootstrap.bind(serverConfig.getTcpPort()).sync();

        log.info("nettyServer run success,TCP-PORT:{}",serverConfig.getTcpPort());
        if(businessConfig.getIsOpenClient()){
            //启动从链路
            this.runClient(future.channel().eventLoop());
        }
        //等待socket被关闭
        future.channel().closeFuture().sync();
    } catch (Exception e){
        log.error("nettyServer run fail");
        e.printStackTrace();
    } finally {
        workGroup.shutdownGracefully();
        boosGroup.shutdownGracefully();
    }

}
 
Example 12
Source File: NettyServer.java    From openzaly with Apache License 2.0 4 votes vote down vote up
public NettyServer() {
	try {
		bootstrap = new ServerBootstrap();
		int needThreadNum = Runtime.getRuntime().availableProcessors() + 1;
		int parentNum = 10;// accept from channel socket
		int childNum = needThreadNum * 5 + 10;// give to business handler
		// 处理服务端事件组
		parentGroup = new NioEventLoopGroup(parentNum, new PrefixThreadFactory("bim-boss-evenloopgroup"));
		// 处理客户端连接请求的事件组
		childGroup = new NioEventLoopGroup(childNum, new PrefixThreadFactory("bim-worker-evenloopgroup"));
		// 用户处理所有的channel
		bootstrap.group(parentGroup, childGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		/**
		 * 对应的是tcp/ip协议listen函数中的backlog参数,函数listen(int socketfd,int
		 * backlog)用来初始化服务端可连接队列. 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接,多个客户端来的时候,
		 * 服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小
		 */
		bootstrap.option(ChannelOption.SO_BACKLOG, 2000);
		/**
		 * 允许监听的端口共存
		 */
		bootstrap.option(ChannelOption.SO_REUSEADDR, true);
		/**
		 * ChannelOption.SO_SNDBUF参数对应于套接字选项中的SO_SNDBUF,
		 * ChannelOption.SO_RCVBUF参数对应于套接字选项中的SO_RCVBUF这两个参数
		 * 用于操作接收缓冲区和发送缓冲区的大小,接收缓冲区用于保存网络协议站内收到的数据, 直到应用程序读取成功,发送缓冲区用于保存发送数据,直到发送成
		 */
		bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
		bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节
		/**
		 * 在4.x版本中,UnpooledByteBufAllocator是默认的allocator,尽管其存在某些限制。
		 * 现在PooledByteBufAllocator已经广泛使用一段时间,并且我们有了增强的缓冲区泄漏追踪机制,
		 * 所以是时候让PooledByteBufAllocator成为默认了。<br>
		 * 总结:Netty4使用对象池,重用缓冲区
		 */
		bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。
		 */
		bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		/**
		 * Nagle算法是将小的数据包组装为更大的帧然后进行发送,而不是输入一次发送一次, 因此在数据包不足的时候会等待其他数据的到了,组装成大的数据包进行发送,
		 * 虽然该方式有效提高网络的有效负载, 但是却造成了延时,
		 * 而该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输,于TCP_NODELAY相对应的是TCP_CORK,
		 * 该选项是需要等到发送的数据量最大的时候,一次性发送
		 */
		bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 接受缓存区,动态内存分配端的算法
		 */
		bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
		// the ChannelHandler to use for serving the requests.
		bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));
		// Set the ChannelHandler which is used to serve the request for the
		// Channel's
		bootstrap.childHandler(new NettyChannelInitializer());

		executor = new SimpleExecutor<Command, CommandResponse>();
		loadExecutor(executor);
	} catch (Exception e) {
		closeGracefully();
		logger.error(AkxProject.PLN + " init openzaly netty-server error.", e);
		System.exit(-10);
	}
}
 
Example 13
Source File: NettyServer.java    From openzaly with Apache License 2.0 4 votes vote down vote up
public NettyServer() {
	try {
		bootstrap = new ServerBootstrap();
		int needThreadNum = Runtime.getRuntime().availableProcessors() + 1;
		int parentNum = 10;// accept from channel socket
		int childNum = needThreadNum * 5 + 10;// give to business handler
		// 处理服务端事件组
		parentGroup = new NioEventLoopGroup(parentNum, new PrefixThreadFactory("bim-boss-evenloopgroup"));
		// 处理客户端连接请求的事件组
		childGroup = new NioEventLoopGroup(childNum, new PrefixThreadFactory("bim-worker-evenloopgroup"));
		// 用户处理所有的channel
		bootstrap.group(parentGroup, childGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		/**
		 * 对应的是tcp/ip协议listen函数中的backlog参数,函数listen(int socketfd,int
		 * backlog)用来初始化服务端可连接队列. 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接,多个客户端来的时候,
		 * 服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小
		 */
		bootstrap.option(ChannelOption.SO_BACKLOG, 2000);
		/**
		 * 允许监听的端口共存
		 */
		bootstrap.option(ChannelOption.SO_REUSEADDR, true);
		/**
		 * ChannelOption.SO_SNDBUF参数对应于套接字选项中的SO_SNDBUF,
		 * ChannelOption.SO_RCVBUF参数对应于套接字选项中的SO_RCVBUF这两个参数
		 * 用于操作接收缓冲区和发送缓冲区的大小,接收缓冲区用于保存网络协议站内收到的数据, 直到应用程序读取成功,发送缓冲区用于保存发送数据,直到发送成
		 */
		bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
		bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节
		/**
		 * 在4.x版本中,UnpooledByteBufAllocator是默认的allocator,尽管其存在某些限制。
		 * 现在PooledByteBufAllocator已经广泛使用一段时间,并且我们有了增强的缓冲区泄漏追踪机制,
		 * 所以是时候让PooledByteBufAllocator成为默认了。<br>
		 * 总结:Netty4使用对象池,重用缓冲区
		 */
		bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。
		 */
		bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		/**
		 * Nagle算法是将小的数据包组装为更大的帧然后进行发送,而不是输入一次发送一次, 因此在数据包不足的时候会等待其他数据的到了,组装成大的数据包进行发送,
		 * 虽然该方式有效提高网络的有效负载, 但是却造成了延时,
		 * 而该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输,于TCP_NODELAY相对应的是TCP_CORK,
		 * 该选项是需要等到发送的数据量最大的时候,一次性发送
		 */
		bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 接受缓存区,动态内存分配端的算法
		 */
		bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
		// the ChannelHandler to use for serving the requests.
		bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));
		// Set the ChannelHandler which is used to serve the request for the
		// Channel's
		bootstrap.childHandler(new NettyChannelInitializer());

		executor = new SimpleExecutor<Command, CommandResponse>();
		loadExecutor(executor);
	} catch (Exception e) {
		closeGracefully();
		logger.error(AkxProject.PLN + " init openzaly netty-server error.", e);
		System.exit(-10);
	}
}
 
Example 14
Source File: NettyServerImpl.java    From sctp with GNU Affero General Public License v3.0 4 votes vote down vote up
private void initSocket() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    b.group(this.management.getBossGroup(), this.management.getWorkerGroup());
    if (this.ipChannelType == IpChannelType.SCTP) {
        b.channel(NioSctpServerChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childHandler(new NettySctpServerChannelInitializer(this, this.management));
        this.applySctpOptions(b);
    } else {
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 100);
        b.childHandler(new NettyTcpServerChannelInitializer(this, this.management));
    }
    b.handler(new LoggingHandler(LogLevel.INFO));

    InetSocketAddress localAddress = new InetSocketAddress(this.hostAddress, this.hostport);

    // Bind the server to primary address.
    ChannelFuture channelFuture = b.bind(localAddress).sync();

    // Get the underlying sctp channel
    if (this.ipChannelType == IpChannelType.SCTP) {
        this.serverChannelSctp = (SctpServerChannel) channelFuture.channel();

        // Bind the secondary address.
        // Please note that, bindAddress in the client channel should be done before connecting if you have not
        // enable Dynamic Address Configuration. See net.sctp.addip_enable kernel param
        if (this.extraHostAddresses != null) {
            for (int count = 0; count < this.extraHostAddresses.length; count++) {
                String localSecondaryAddress = this.extraHostAddresses[count];
                InetAddress localSecondaryInetAddress = InetAddress.getByName(localSecondaryAddress);

                channelFuture = this.serverChannelSctp.bindAddress(localSecondaryInetAddress).sync();
            }
        }

        if (logger.isInfoEnabled()) {
            logger.info(String.format("SctpServerChannel bound to=%s ", this.serverChannelSctp.allLocalAddresses()));
        }
    } else {
        this.serverChannelTcp = (NioServerSocketChannel) channelFuture.channel();

        if (logger.isInfoEnabled()) {
            logger.info(String.format("ServerSocketChannel bound to=%s ", this.serverChannelTcp.localAddress()));
        }
    }
}
 
Example 15
Source File: NettyServer.java    From wind-im with Apache License 2.0 4 votes vote down vote up
public NettyServer() {
	try {
		bootstrap = new ServerBootstrap();
		int needThreadNum = Runtime.getRuntime().availableProcessors() + 1;
		int parentNum = 10;// accept from channel socket
		int childNum = needThreadNum * 5 + 10;// give to business handler
		// 处理服务端事件组
		parentGroup = new NioEventLoopGroup(parentNum, new PrefixThreadFactory("bim-boss-evenloopgroup"));
		// 处理客户端连接请求的事件组
		childGroup = new NioEventLoopGroup(childNum, new PrefixThreadFactory("bim-worker-evenloopgroup"));
		// 用户处理所有的channel
		bootstrap.group(parentGroup, childGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		/**
		 * 对应的是tcp/ip协议listen函数中的backlog参数,函数listen(int socketfd,int
		 * backlog)用来初始化服务端可连接队列. 服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接,多个客户端来的时候,
		 * 服务端将不能处理的客户端连接请求放在队列中等待处理,backlog参数指定了队列的大小
		 */
		bootstrap.option(ChannelOption.SO_BACKLOG, 2000);
		/**
		 * 允许监听的端口共存
		 */
		bootstrap.option(ChannelOption.SO_REUSEADDR, true);
		/**
		 * ChannelOption.SO_SNDBUF参数对应于套接字选项中的SO_SNDBUF,
		 * ChannelOption.SO_RCVBUF参数对应于套接字选项中的SO_RCVBUF这两个参数
		 * 用于操作接收缓冲区和发送缓冲区的大小,接收缓冲区用于保存网络协议站内收到的数据, 直到应用程序读取成功,发送缓冲区用于保存发送数据,直到发送成
		 */
		bootstrap.option(ChannelOption.SO_RCVBUF, 256 * 1024);
		bootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);// 256 KB/字节
		/**
		 * 在4.x版本中,UnpooledByteBufAllocator是默认的allocator,尽管其存在某些限制。
		 * 现在PooledByteBufAllocator已经广泛使用一段时间,并且我们有了增强的缓冲区泄漏追踪机制,
		 * 所以是时候让PooledByteBufAllocator成为默认了。<br>
		 * 总结:Netty4使用对象池,重用缓冲区
		 */
		bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 当设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文。
		 */
		bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
		/**
		 * Nagle算法是将小的数据包组装为更大的帧然后进行发送,而不是输入一次发送一次, 因此在数据包不足的时候会等待其他数据的到了,组装成大的数据包进行发送,
		 * 虽然该方式有效提高网络的有效负载, 但是却造成了延时,
		 * 而该参数的作用就是禁止使用Nagle算法,使用于小数据即时传输,于TCP_NODELAY相对应的是TCP_CORK,
		 * 该选项是需要等到发送的数据量最大的时候,一次性发送
		 */
		bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
		bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		/**
		 * 接受缓存区,动态内存分配端的算法
		 */
		bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT);
		// the ChannelHandler to use for serving the requests.
		bootstrap.handler(new LoggingHandler(LogLevel.DEBUG));
		// Set the ChannelHandler which is used to serve the request for the
		// Channel's
		bootstrap.childHandler(new NettyChannelInitializer());

		executor = new SimpleExecutor<Command, CommandResponse>();
		loadExecutor(executor);
	} catch (Exception e) {
		closeGracefully();
		logger.error(AkxProject.PLN + " init openzaly netty-server error.", e);
		System.exit(-10);
	}
}
 
Example 16
Source File: PeerServer.java    From ethereumj with MIT License 4 votes vote down vote up
public void start(int port) {


        inactivesCollector.scheduleAtFixedRate(new TimerTask() {
            public void run() {

                Iterator<Channel> iter = channels.iterator();
                while(iter.hasNext()){
                    Channel channel = iter.next();
                    if(!channel.p2pHandler.isActive()){

                        iter.remove();
                        logger.info("Channel removed: {}", channel.p2pHandler.getHandshakeHelloMessage());
                    }
                }
            }
        }, 2000, 5000);


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

        if (peerListener != null)
        	peerListener.console("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(new EthereumChannelInitializer(this));

            // Start the client.
            logger.info("Listening for incoming connections, port: [{}] ", port);
            ChannelFuture f = b.bind(port).sync();

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

        } catch (Exception e) {
        	logger.debug("Exception: {} ({})", e.getMessage(), e.getClass().getName());
            throw new Error("Server Disconnnected");
        } finally {
        	workerGroup.shutdownGracefully();

        }
    }
 
Example 17
Source File: NettyServer.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
public void start(int listenOn) throws Exception {
    if (started.compareAndSet(false, true)) {

        // Basic server configuration with NIO only options.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();
        server.group(bossGroup, workerGroup);
        server.channel(NioServerSocketChannel.class);
        server.option(ChannelOption.SO_BACKLOG, 100);
        server.handler(new LoggingHandler(LogLevel.INFO));
        server.childHandler(new ChannelInitializer<Channel>() {

            @Override
            public void initChannel(Channel ch) throws Exception {
                if (isSecureServer()) {
                    SSLContext context = TransportSupport.createJdkSslContext(options);
                    SSLEngine engine = TransportSupport.createJdkSslEngine(null, context, options);
                    engine.setUseClientMode(false);
                    engine.setNeedClientAuth(needClientAuth);
                    sslHandler = new SslHandler(engine);
                    ch.pipeline().addLast(sslHandler);
                }

                if (webSocketServer) {
                    ch.pipeline().addLast(new HttpServerCodec());
                    ch.pipeline().addLast(new HttpObjectAggregator(65536));
                    ch.pipeline().addLast(new WebSocketServerProtocolHandler(getWebSocketPath(), "amqp", true, maxFrameSize));
                }

                ch.pipeline().addLast(new NettyServerOutboundHandler());
                ch.pipeline().addLast(new NettyServerInboundHandler());
                ch.pipeline().addLast(getServerHandler());
            }
        });

        // Start the server using specified port.  If value is zero the server
        // will select a free port and so we update the server port value after
        // in order to reflect the correct value.
        serverChannel = server.bind(listenOn).sync().channel();
        serverPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    }
}