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

The following examples show how to use io.netty.channel.socket.nio.NioServerSocketChannel. 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: MatchServer.java    From Almost-Famous with MIT License 6 votes vote down vote up
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();
        }
    }
}
 
Example #2
Source File: NettyServerTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: TransportServerSupport.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: NettyServer.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 启动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");
    }
}
 
Example #5
Source File: Server.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: NettyClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #7
Source File: KQueueSocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: HttpServer.java    From smartacus-mqtt-broker with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception{
    EventLoopGroup bossGroup=new NioEventLoopGroup(1);
    NioEventLoopGroup  workerGroup=new NioEventLoopGroup();
    try{
        //实例化session工厂和connection工厂
        ServerBootstrap sboot=new ServerBootstrap();
        sboot.group(bossGroup,workerGroup)
                //设置通道类型
                .channel(NioServerSocketChannel.class)
                //向通道的中添加handler初始化器
                .childHandler(new HttpChannelChannelInitializer())
                .option(ChannelOption.SO_BACKLOG,64)
                //设置子Socket的keepalive时间
                .childOption(ChannelOption.SO_KEEPALIVE,true);
        //绑定端口号
        ChannelFuture cf = sboot.bind(18088).sync();
        cf.channel().closeFuture().sync();
    }finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #9
Source File: HttpCorsServer.java    From netty-4.1.22 with Apache License 2.0 6 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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new HttpCorsServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #10
Source File: CustomProtocolServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #11
Source File: IOTGatewayServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #12
Source File: IOTMqttServer.java    From IOT-Technical-Guide with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #13
Source File: WorldClockServer.java    From netty-4.1.22 with Apache License 2.0 6 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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new WorldClockServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #14
Source File: Http2Server.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #15
Source File: TcpBroker.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #16
Source File: NettyServerTransport.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 配置
 *
 * @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;
}
 
Example #17
Source File: TelnetServer.java    From netty-4.1.22 with Apache License 2.0 6 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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new TelnetServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #18
Source File: SocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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);
                }
            }
    );
}
 
Example #19
Source File: TCPServer.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
ChannelFuture bing() {
    ChannelFuture channelFuture = null;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)    //非阻塞模式
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, keepAlive)
                .option(ChannelOption.SO_BACKLOG, backlog)
                .childHandler(new WSServerInitialzer(nettyHandlerService));

        channelFuture = b.bind(new InetSocketAddress(tcpPort)).syncUninterruptibly();
        channel = channelFuture.channel();
    } catch (Exception e) {
        log.error("netty start error {}  {}", e.getMessage(), e);
    } finally {
        if (null != channelFuture && channelFuture.isSuccess()) {
            log.info("tCPServerTwo start ok");
        } else {
            log.error("tCPServerTwo start error ");
        }
    }
    return channelFuture;
}
 
Example #20
Source File: NettyServer.java    From EasyChatServer with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #21
Source File: PortListenerAbstract.java    From iot-dc with Apache License 2.0 6 votes vote down vote up
/**
 * 接口绑定
 */
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();
    }
}
 
Example #22
Source File: AutobahnServer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #23
Source File: TransportServerSupport.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #24
Source File: NettyTcpServer.java    From jt808-netty with MIT License 6 votes vote down vote up
/**
 * 启动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);
    }
}
 
Example #25
Source File: FactorialServer.java    From netty-4.1.22 with Apache License 2.0 6 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)
         .channel(NioServerSocketChannel.class)
         .handler(new LoggingHandler(LogLevel.INFO))
         .childHandler(new FactorialServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
Example #26
Source File: SecureChatServer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #27
Source File: BattleServer.java    From Almost-Famous with MIT License 6 votes vote down vote up
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();
        }
    }
}
 
Example #28
Source File: HexDumpProxy.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #29
Source File: TcpServer.java    From ns4_frame with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #30
Source File: HiveMQNettyBootstrapTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    hiveMQNettyBootstrap = new HiveMQNettyBootstrap(shutdownHooks, listenerConfigurationService, channelInitializerFactoryImpl,
            new NettyConfiguration(NioServerSocketChannel.class, NioSocketChannel.class, new NioEventLoopGroup(1), new NioEventLoopGroup(1)));

    when(channelInitializerFactoryImpl.getChannelInitializer(any(Listener.class))).thenReturn(abstractChannelInitializer);
}