netty同时绑定80和443端口

public static void main(String[] args) throws Exception {
        ContextProvider.onStart();
        File keyFile = new File("/out/my.pk8"); //使用pkcs8格式的私钥
        File crtFile = new File("/out/my.crt");
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            /** 使用已有的证书 */
            final SslContext ctx = SslContextBuilder.forServer(crtFile /** 此处为证书, 不是公钥 */,
                    keyFile /** 私钥*/, "123456" /** 私钥密码, 如果没有密码则不填 */).build();
             /** 让netty随机生成证书 */
            //SelfSignedCertificate cert = new SelfSignedCertificate();
            //final SslContext ctx = SslContext.newServerContext(cert.certificate(), cert.privateKey());                    
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3)
                    .childHandler(new ChannelInitializer() { // (4)
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipe = ch.pipeline();
                            if (ch.localAddress().getPort() == 443) {
                            	/** 如果是443端口, 则需要添加ssl处理器 */
                                pipe.addLast(ctx.newHandler(ch.alloc()));
                            }
                            pipe.addLast(new RtspDecoder()).addLast(new RTSPHandler());
                            pipe.addLast(new ReadTimeoutHandler(30));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
            List futures = new ArrayList<>();
            futures.add(b.bind(80));
            futures.add(b.bind(443));
            for (ChannelFuture f : futures) {
                f.channel().closeFuture().sync();
            }
        } catch (Exception ex) {
            logger.error("start netty failed, ", ex);
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

你可能感兴趣的:(后端)