1. 程式人生 > >netty同時繫結80和443埠

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<SocketChannel>() { // (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<ChannelFuture> 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();
        }
    }