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();
}
}
netty同时绑定80和443端口
最新推荐文章于 2024-04-09 16:15:29 发布