类io.netty.channel.socket.nio.NioServerSocketChannel源码实例Demo

下面列出了怎么用io.netty.channel.socket.nio.NioServerSocketChannel的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: journalkeeper   文件: TransportServerSupport.java
protected ServerBootstrap newBootstrap(ChannelHandler channelHandler, EventLoopGroup acceptEventGroup, EventLoopGroup ioEventGroup) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(acceptEventGroup, ioEventGroup)
            .childHandler(channelHandler)
            .option(ChannelOption.SO_REUSEADDR, serverConfig.isReuseAddress())
            .option(ChannelOption.SO_RCVBUF, serverConfig.getSocketBufferSize())
            .option(ChannelOption.SO_BACKLOG, serverConfig.getBacklog())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_SNDBUF, serverConfig.getSocketBufferSize())
            .childOption(ChannelOption.TCP_NODELAY, serverConfig.isTcpNoDelay())
            .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.isKeepAlive())
            .childOption(ChannelOption.SO_LINGER, serverConfig.getSoLinger())
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return serverBootstrap;
}
 
@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<ServerBootstrap>> serverSocket() {
    List<BootstrapFactory<ServerBootstrap>> toReturn = new ArrayList<BootstrapFactory<ServerBootstrap>>();
    toReturn.add(new BootstrapFactory<ServerBootstrap>() {
        @Override
        public ServerBootstrap newInstance() {
            return new ServerBootstrap().group(KQUEUE_BOSS_GROUP, KQUEUE_WORKER_GROUP)
                                        .channel(KQueueServerSocketChannel.class);
        }
    });

    toReturn.add(new BootstrapFactory<ServerBootstrap>() {
        @Override
        public ServerBootstrap newInstance() {
            return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup)
                                        .channel(NioServerSocketChannel.class);
        }
    });

    return toReturn;
}
 
源代码3 项目: jt808-server   文件: TCPServer.java
private void bind() throws Exception {
    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(30, 0, 0, TimeUnit.MINUTES));
            // 1024表示单条消息的最大长度,解码器在查找分隔符的时候,达到该长度还没找到的话会抛异常
            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.wrappedBuffer(new byte[]{delimiter}), Unpooled.wrappedBuffer(new byte[]{delimiter, delimiter})));
            ch.pipeline().addLast(inboundHandler);
        }
    });
    serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    this.log.info("TCP服务启动完毕,port={}", this.port);
    ChannelFuture channelFuture = serverBootstrap.bind(port).sync();

    channelFuture.channel().closeFuture().sync();
}
 
源代码4 项目: grpc-nebula-java   文件: NettyServerTest.java
@Test
public void getPort_notStarted() throws Exception {
  InetSocketAddress addr = new InetSocketAddress(0);
  NettyServer ns = new NettyServer(
      addr,
      NioServerSocketChannel.class,
      new HashMap<ChannelOption<?>, Object>(),
      null, // no boss group
      null, // no event group
      new ProtocolNegotiators.PlaintextNegotiator(),
      Collections.<ServerStreamTracer.Factory>emptyList(),
      TransportTracer.getDefaultFactory(),
      1, // ignore
      1, // ignore
      1, // ignore
      1, // ignore
      1, // ignore
      1, 1, // ignore
      1, 1, // ignore
      true, 0, // ignore
      channelz);

  assertThat(ns.getPort()).isEqualTo(-1);
}
 
private void startServer(int maxStreamsPerConnection, int maxHeaderListSize) throws IOException {
  server = new NettyServer(
      TestUtils.testServerAddress(0),
      NioServerSocketChannel.class,
      new HashMap<ChannelOption<?>, Object>(),
      group, group, negotiator,
      Collections.<ServerStreamTracer.Factory>emptyList(),
      TransportTracer.getDefaultFactory(),
      maxStreamsPerConnection,
      DEFAULT_WINDOW_SIZE, DEFAULT_MAX_MESSAGE_SIZE, maxHeaderListSize,
      DEFAULT_SERVER_KEEPALIVE_TIME_NANOS, DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS,
      MAX_CONNECTION_IDLE_NANOS_DISABLED,
      MAX_CONNECTION_AGE_NANOS_DISABLED, MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE, true, 0,
      channelz);
  server.start(serverListener);
  address = TestUtils.testServerAddress(server.getPort());
  authority = GrpcUtil.authorityFromHostAndPort(address.getHostString(), address.getPort());
}
 
源代码6 项目: netty-4.1.22   文件: Server.java
public static void main(String[] args) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new ServerHandler());
                }
            });
    ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress("172.28.86.151",8080)).sync();
    channelFuture.channel().closeFuture().sync();
    bossGroup.shutdownGracefully();
    workGroup.shutdownGracefully();
}
 
源代码7 项目: spring-boot-demo   文件: NettyServer.java
/**
 * 启动Netty Server
 *
 * @throws InterruptedException
 */
@PostConstruct
public void start() throws InterruptedException {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, work)
            // 指定Channel
            .channel(NioServerSocketChannel.class)
            //使用指定的端口设置套接字地址
            .localAddress(new InetSocketAddress(port))

            //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
            .option(ChannelOption.SO_BACKLOG, 1024)

            //设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
            .childOption(ChannelOption.SO_KEEPALIVE, true)

            //将小的数据包包装成更大的帧进行传送,提高网络的负载
            .childOption(ChannelOption.TCP_NODELAY, true)

            .childHandler(new ServerChannelInitializer());
    ChannelFuture future = bootstrap.bind().sync();
    if (future.isSuccess()) {
        log.info("启动 Netty Server");
    }
}
 
源代码8 项目: smartacus-mqtt-broker   文件: HttpServer.java
public void run() throws Exception{
    EventLoopGroup bossGroup=new NioEventLoopGroup(1);
    NioEventLoopGroup  workerGroup=new NioEventLoopGroup();
    try{
        //实例化session工厂和connection工厂
        ServerBootstrap sboot=new ServerBootstrap();
        sboot.group(bossGroup,workerGroup)
                //设置通道类型
                .channel(NioServerSocketChannel.class)
                //向通道的中添加handler初始化器
                .childHandler(new HttpChannelChannelInitializer())
                .option(ChannelOption.SO_BACKLOG,64)
                //设置子Socket的keepalive时间
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        //绑定端口号
        ChannelFuture cf = sboot.bind(18088).sync();
        cf.channel().closeFuture().sync();
    }finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
源代码9 项目: netty-4.1.22   文件: HttpCorsServer.java
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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpCorsServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码10 项目: IOT-Technical-Guide   文件: CustomProtocolServer.java
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new CustomProtocolInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码11 项目: IOT-Technical-Guide   文件: IOTGatewayServer.java
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new GatewayTransportServerInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码12 项目: IOT-Technical-Guide   文件: IOTMqttServer.java
public static void main(String[] args) throws Exception {
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

    EventLoopGroup bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
    EventLoopGroup workerGroup = new NioEventLoopGroup(workerGroupThreadCount);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new MqttTransportServerInitializer(maxPayloadSize));
        ChannelFuture f = b.bind(PORT);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码13 项目: netty-4.1.22   文件: WorldClockServer.java
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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new WorldClockServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码14 项目: netty-4.1.22   文件: Http2Server.java
void run() throws Exception {
    // 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());

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

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
源代码15 项目: WeEvent   文件: TcpBroker.java
private Channel tcpServer(int port) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(this.bossGroup, this.workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    channelPipeline.addFirst("idle", new IdleStateHandler(
                            0,
                            0,
                            weEventConfig.getKeepAlive()));

                    //channelPipeline.addLast("ssl", getSslHandler(sslContext, socketChannel.alloc()));
                    channelPipeline.addLast("decoder", new MqttDecoder());
                    channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    channelPipeline.addLast("broker", new TcpHandler(protocolProcess));
                }
            });
    return serverBootstrap.bind(port).sync().channel();
}
 
源代码16 项目: joyrpc   文件: NettyServerTransport.java
/**
 * 配置
 *
 * @param bootstrap
 * @param sslContext
 */
protected ServerBootstrap configure(final ServerBootstrap bootstrap, final SslContext sslContext) {
    //io.netty.bootstrap.Bootstrap - Unknown channel option 'SO_BACKLOG' for channel
    bootstrap.channel(Constants.isUseEpoll(url) ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new MyChannelInitializer(url, sslContext))
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, url.getPositiveInt(Constants.CONNECT_TIMEOUT_OPTION))
            .option(ChannelOption.SO_REUSEADDR, url.getBoolean(Constants.SO_REUSE_PORT_OPTION))
            .option(ChannelOption.SO_BACKLOG, url.getPositiveInt(Constants.SO_BACKLOG_OPTION))
            .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
            .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(url.getPositiveInt(Constants.WRITE_BUFFER_LOW_WATERMARK_OPTION),
                    url.getPositiveInt(Constants.WRITE_BUFFER_HIGH_WATERMARK_OPTION)))
            .childOption(ChannelOption.SO_RCVBUF, url.getPositiveInt(Constants.SO_RECEIVE_BUF_OPTION))
            .childOption(ChannelOption.SO_SNDBUF, url.getPositiveInt(Constants.SO_SEND_BUF_OPTION))
            .childOption(ChannelOption.SO_KEEPALIVE, url.getBoolean(Constants.SO_KEEPALIVE_OPTION))
            .childOption(ChannelOption.TCP_NODELAY, url.getBoolean(Constants.TCP_NODELAY))
            .childOption(ChannelOption.ALLOCATOR, BufAllocator.create(url));

    return bootstrap;
}
 
源代码17 项目: ns4_frame   文件: TcpServer.java
@Override
public void startUp() throws Exception {
    initLog.info("启动Tcp服务");
    tcpBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
    tcpBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    tcpBootstrap.group(bossGroup, workerGroup);
    tcpBootstrap.channel(NioServerSocketChannel.class);
    tcpBootstrap.handler(new NSLogginHandler(LogLevel.INFO));
    tcpBootstrap.childHandler(new TcpServerInitializer());

    try {
        Channel ch = tcpBootstrap.bind(ConfigCenter.getConfig.getTcpPort()).sync().channel();
        ch.closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
        destroy();
    }
}
 
源代码18 项目: netty-4.1.22   文件: TelnetServer.java
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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new TelnetServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码19 项目: netty-4.1.22   文件: SocketTestPermutation.java
public List<BootstrapFactory<ServerBootstrap>> serverSocket() {
    return Arrays.asList(
            new BootstrapFactory<ServerBootstrap>() {
                @Override
                public ServerBootstrap newInstance() {
                    return new ServerBootstrap().group(nioBossGroup, nioWorkerGroup)
                            .channel(NioServerSocketChannel.class);
                }
            },
            new BootstrapFactory<ServerBootstrap>() {
                @Override
                public ServerBootstrap newInstance() {
                    return new ServerBootstrap().group(oioBossGroup, oioWorkerGroup)
                            .channel(OioServerSocketChannel.class)
                            .option(ChannelOption.SO_TIMEOUT, OIO_SO_TIMEOUT);
                }
            }
    );
}
 
源代码20 项目: momo-cloud-permission   文件: TCPServer.java
ChannelFuture bing() {
    ChannelFuture channelFuture = null;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)    //非阻塞模式
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, keepAlive)
                .option(ChannelOption.SO_BACKLOG, backlog)
                .childHandler(new WSServerInitialzer(nettyHandlerService));

        channelFuture = b.bind(new InetSocketAddress(tcpPort)).syncUninterruptibly();
        channel = channelFuture.channel();
    } catch (Exception e) {
        log.error("netty start error {}  {}", e.getMessage(), e);
    } finally {
        if (null != channelFuture && channelFuture.isSuccess()) {
            log.info("tCPServerTwo start ok");
        } else {
            log.error("tCPServerTwo start error ");
        }
    }
    return channelFuture;
}
 
源代码21 项目: EasyChatServer   文件: NettyServer.java
private void open(int port) throws Exception {
    bootstrap = new ServerBootstrap();
    boss = new NioEventLoopGroup();
    worker = new NioEventLoopGroup();

    bootstrap
            .group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .childHandler(workServerInitializer);
    ChannelFuture channelFuture = bootstrap.bind(port).sync();
    log.info("netty 服务启动成功, 端口 = {}", port);
    channel = channelFuture.channel();
    
    //关闭监听服务器
    channel.closeFuture().sync();
}
 
源代码22 项目: iot-dc   文件: PortListenerAbstract.java
/**
 * 接口绑定
 */
void bind() {
    if (port == 0 || this.workerGroup == null || this.bossGroup == null) {
        throw new RuntimeException("'port','bossGroup' and 'workerGroup' had to be initialized before bind.");
    }

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(this.bossGroup, this.workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(this.settingChannelInitializerHandler());
        ChannelFuture channelFuture = bootstrap.bind(this.port).sync();
        LOGGER.info("port:{} bind successful.", port);
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码23 项目: netty-4.1.22   文件: AutobahnServer.java
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
         .childHandler(new AutobahnServerInitializer());

        ChannelFuture f = b.bind(port).sync();
        System.out.println("Web Socket Server started at port " + port);
        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码24 项目: joyqueue   文件: TransportServerSupport.java
protected ServerBootstrap newBootstrap(ChannelHandler channelHandler, EventLoopGroup acceptEventGroup, EventLoopGroup ioEventGroup) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(Epoll.isAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .group(acceptEventGroup, ioEventGroup)
            .childHandler(channelHandler)
            .option(ChannelOption.SO_REUSEADDR, config.isReuseAddress())
            .option(ChannelOption.SO_RCVBUF, config.getSocketBufferSize())
            .option(ChannelOption.SO_BACKLOG, config.getBacklog())
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_SNDBUF, config.getSocketBufferSize())
            .childOption(ChannelOption.TCP_NODELAY, config.isTcpNoDelay())
            .childOption(ChannelOption.SO_KEEPALIVE, config.isKeepAlive())
            .childOption(ChannelOption.SO_LINGER, config.getSoLinger())
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    return serverBootstrap;
}
 
源代码25 项目: jt808-netty   文件: NettyTcpServer.java
/**
 * 启动Server
 *
 * @throws InterruptedException
 */
@PostConstruct
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(jt808ChannelInitializer)
            .option(ChannelOption.SO_BACKLOG, 1024) //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
            .childOption(ChannelOption.TCP_NODELAY, true)//立即写出
            .childOption(ChannelOption.SO_KEEPALIVE, true);//长连接
    ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.SIMPLE);//内存泄漏检测 开发推荐PARANOID 线上SIMPLE
    ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
    if (channelFuture.isSuccess()) {
        log.info("TCP服务启动完毕,port={}", this.port);
    }
}
 
源代码26 项目: netty-4.1.22   文件: FactorialServer.java
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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new FactorialServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码27 项目: netty-4.1.22   文件: SecureChatServer.java
public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
        .build();

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

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码28 项目: Almost-Famous   文件: BattleServer.java
public void start() {
    synchronized (waitLock) {
        int port = battleServerConfig.getPort();
        try {
            server.group(boss, work);
            server.channel(NioServerSocketChannel.class);
            server.childHandler(battleServerInitializer);
            log.info("匹配服务器在[{}]端口启动监听", port);
            ChannelFuture future = server.bind(port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("[出现异常] 释放资源", e);
        }finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
 
源代码29 项目: netty-4.1.22   文件: HexDumpProxy.java
public static void main(String[] args) throws Exception {
    System.err.println("Proxying *:" + LOCAL_PORT + " to " + REMOTE_HOST + ':' + REMOTE_PORT + " ...");

    // Configure the bootstrap.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HexDumpProxyInitializer(REMOTE_HOST, REMOTE_PORT))
         .childOption(ChannelOption.AUTO_READ, false)
         .bind(LOCAL_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码30 项目: Almost-Famous   文件: MatchServer.java
public void start() {
    synchronized (waitLock) {
        int port = matchServerConfig.getPort();
        try {
            b.group(boss, work);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(battleServerInitializer);
            log.info("匹配服务器在[{}]端口启动监听", port);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("[出现异常] 释放资源", e);
        } finally {
            work.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
 
 类所在包
 类方法
 同包方法