TsgcHTTP3Server

TsgcHTTP3Server 实现了一个 HTTP/3 服务器(RFC 9114),通过 QUIC 处理 HTTP 请求。

简介

TsgcHTTP3Server 按照 RFC 9114 定义实现了一个 HTTP/3 服务器。HTTP/3 通过 QUIC(一种内置 TLS 1.3 的基于 UDP 的传输协议)承载 HTTP 请求和响应,因此每个连接均已加密和多路复用,且不存在队头阻塞。服务器默认运行在 OpenSSL 3.5 或更高版本提供的原生 QUIC 监听器上,当该监听器不可用时回退到 sgc QUIC 引擎(参阅 QUICMode),因此无需外部 HTTP/3 库。

请按照以下步骤配置此组件:

1. 创建 TsgcHTTP3Server 的新实例,并设置服务器将监听的 Port(HTTP/3 使用 UDP)。

2. 在 QUICOptions.SSLOptions 中设置证书和私钥。QUIC 要求 TLS,因此证书为必填项。

3. 处理 OnH3Request 事件,填写响应并调用 Start。aResponse 参数由服务器创建(状态码默认为 200);设置其 StatusCode、ContentType 和正文,处理程序返回时服务器将自动发送响应。示例:


    oServer := TsgcHTTP3Server.Create(nil);
    oServer.Port := 443;
    oServer.QUICOptions.SSLOptions.CertFile := 'cert.pem';
    oServer.QUICOptions.SSLOptions.KeyFile := 'key.pem';
    oServer.OnH3Request := OnH3RequestEvent;
    oServer.Start;

    procedure OnH3RequestEvent(Sender: TObject; const aConnection:
        TsgcQUICServerConnection; const aRequest: TsgcHTTP3Request;
        const aResponse: TsgcHTTP3Response);
    begin
      aResponse.StatusCode := 200;
      aResponse.ContentType := 'text/plain';
      aResponse.Data := TEncoding.UTF8.GetBytes('Hello HTTP/3');
    end;

参考

关键属性

名称描述
PortHTTP/3 服务器监听的 UDP 端口。
QUICOptionsQUIC 传输选项,包括证书、私钥和连接限制。
H3Settings向对等方通告的 HTTP/3 协议设置(QPACK 及字段节大小限制)。

关键方法

名称描述
Start启动 QUIC 监听器并开始接受 HTTP/3 连接。
Stop停止监听器并关闭所有活动连接。
SendResponse在请求流上发送 HTTP/3 响应。

关键事件

名称描述
OnH3Request收到完整 HTTP/3 请求时触发,以便应用程序填写响应。
OnH3Connect当客户端建立 HTTP/3 连接时触发。
OnH3DisconnectHTTP/3 连接关闭时触发。

完整示例

以下示例启动一个 HTTP/3 服务器,路由几条路径并返回 JSON 或纯文本正文。响应在 OnH3Request 内填写并由服务器自动发送。


oServer := TsgcHTTP3Server.Create(nil);
oServer.Port := 443;
oServer.QUICOptions.SSLOptions.CertFile := 'cert.pem';
oServer.QUICOptions.SSLOptions.KeyFile := 'key.pem';
oServer.OnH3Request := OnH3RequestEvent;
oServer.OnH3Connect := OnH3ConnectEvent;
oServer.OnH3Disconnect := OnH3DisconnectEvent;
oServer.Start;

procedure OnH3ConnectEvent(Sender: TObject; const aConnection:
    TsgcQUICServerConnection);
begin
  Log('HTTP/3 client connected: ' + aConnection.PeerIP);
end;

procedure OnH3DisconnectEvent(Sender: TObject; const aConnection:
    TsgcQUICServerConnection; aCode: Int64; const aReason: string);
begin
  Log('HTTP/3 client disconnected');
end;

procedure OnH3RequestEvent(Sender: TObject; const aConnection:
    TsgcQUICServerConnection; const aRequest: TsgcHTTP3Request;
    const aResponse: TsgcHTTP3Response);
begin
  if aRequest.Path = '/api/time' then
  begin
    aResponse.StatusCode := 200;
    aResponse.ContentType := 'application/json';
    aResponse.Data := TEncoding.UTF8.GetBytes(
      '{"time":"' + DateTimeToStr(Now) + '"}');
  end
  else
  begin
    aResponse.StatusCode := 404;
    aResponse.ContentType := 'text/plain';
    aResponse.Data := TEncoding.UTF8.GetBytes('Not Found');
  end;
end;

系统要求