Study · Advanced · 3 bài riêng + 1 bài cùng cổng

Chạy từng phiên bản HTTP như một bài riêng.

Giữ nguyên route GET /hello/Ada của bài service đầu tiên. Mỗi bài chỉ thay listener, cách mở cổng và lệnh kiểm tra để kết quả của HTTP/1.1, HTTP/2 và HTTP/3 không bị trộn lẫn.

Chuẩn bị một lần

Chuẩn bị listener theo ngôn ngữ

  1. Cài connector và native SDK theo kênh chính thức trong Study.
  2. Giữ route/handler /hello/{name}; chỉ thay cách khai báo listener.
  3. Đọc capability của exact loaded package. Thiếu HTTP/2 hoặc HTTP/3 thì dừng bài tương ứng.
  4. Dùng port khác nhau khi giữ nhiều service chạy đồng thời.

Chạy dịch vụ ở một terminal và gửi yêu cầu từ terminal thứ hai trên cùng máy. Cả hai terminal đứng ở thư mục dự án, nơi chứa certs/. Dừng dịch vụ theo hướng dẫn của ngôn ngữ đã chọn sau mỗi bài.

Riêng C/C++: ví dụ đầu tiên phục vụ /hello và trả hello native. Thay /hello/Ada bằng /hello trong cả 3 lệnh curl; kiểm tra phiên bản HTTP và mã 200 như bên dưới. Ở bài 1, đặt configuration.port = 8080U.

Các bài hiện tại dùng connector 2.3.2 và Core SDK 2.3.0.

Lab 01 · Beginner baseline · HTTP/1.1

Chứng minh request đầu tiên đi thẳng tới listener HTTP/1.1.

1

Cấu hình

Dùng helper listen("127.0.0.1", 8080), hoặc listener có protocol HTTP/1.1 và security plaintext.

2

Chạy service

Giữ service chạy và xác nhận nó in đúng endpoint loopback.

3

Gửi yêu cầu bằng HTTP/1.1

Terminal
curl -i --max-time 10 --http1.1 http://127.0.0.1:8080/hello/Ada
HTTP/1.1 200 OK
...
hello Ada

Đạt khi: status là 200, body đúng và log/service không có failure. Bài này không chứng minh TLS, HTTP/2 hoặc HTTP/3.

Chuẩn bị cho Lab 02–04

Tạo certificate phát triển cho localhost.

Terminal
mkdir -p certs
openssl req -x509 -newkey rsa:2048 -nodes -days 7 \
  -keyout certs/server-key.pem \
  -out certs/server-chain.pem \
  -subj "/CN=localhost" \
  -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"

server-key.pem là private key, không commit hoặc log. server-chain.pem được truyền cho curl --cacert để bài test vẫn kiểm tra trust; không dùng -k.

Lab 02 · Advanced · HTTP/2

Bật listener HTTP/2 bằng TLS, rồi xác nhận h2.

  1. Tạo chứng chỉ và chọn cấu hình HTTP/2 theo ngôn ngữ, dùng cổng 8443.
  2. Chạy dịch vụ với chứng chỉ và khóa riêng vừa tạo. Dùng địa chỉ HTTPS trong lệnh dưới, kể cả khi ví dụ ban đầu còn in http://.
  3. Tìm dòng ALPN: server accepted h2, sau đó kiểm tra HTTP/2 200 và nội dung hello Ada.
Terminal
curl -isSv --ipv4 --max-time 10 --http2 --cacert certs/server-chain.pem \
  https://localhost:8443/hello/Ada

Đạt khi: client thương lượng h2 trong TLS handshake. ALPN là dòng cho biết hai phía đã đồng ý dùng phiên bản nào. Nếu curl báo không hỗ trợ HTTP/2, kiểm tra dòng Features của curl --version trước khi chẩn đoán dịch vụ.

Lab 03 · Advanced · HTTP/3

Bật listener HTTP/3 trên UDP, rồi ép client dùng HTTP/3.

  1. Chạy curl --version. Nếu dòng Features có HTTP3, thử bản curl đang cài trước. Trên Debian 13, có thể dùng Backports nếu cần bản khác.
  2. Chuẩn bị chứng chỉ và chọn cấu hình HTTP/3 theo ngôn ngữ trên cổng 8444. Bài chạy cùng máy qua 127.0.0.1; không cần mở cổng ra ngoài.
  3. Chạy dịch vụ rồi gửi yêu cầu bằng --http3-only. Nếu không kết nối được bằng HTTP/3, curl báo lỗi thay vì tự chuyển sang HTTP/2 hoặc HTTP/1.1.
Cài curl trên Raspberry PiDebian 13 (Trixie) · cài Backports nếu cần

Kiểm tra VERSION_CODENAME=trixie trong /etc/os-release và dpkg --print-architecture trả arm64. Nếu chưa bật trixie-backports, thêm kho chính thức một lần:

Bật Backports nếu chưa có
printf '%s\n' \
  'deb [signed-by=/usr/share/keyrings/debian-archive-keyring.gpg] https://deb.debian.org/debian trixie-backports main' \
  | sudo tee /etc/apt/sources.list.d/coakka-trixie-backports.list > /dev/null
Cài và kiểm tra curl
sudo apt update
sudo apt install -t trixie-backports curl
/usr/bin/curl --version

Sau khi cài, kiểm tra dòng Features có HTTP3. Trên Pi thử nghiệm, curl 8.14.1 mặc định của Debian đã chạy được với 2.2.1, nên không cần cài Backports. Bản curl 8.21.0 từ Backports cũng chạy đúng HTTP/3 ở bài riêng và bài cùng cổng.

Với Debian 12 (Bookworm) hoặc hệ điều hành khác, dùng gói dành cho hệ điều hành đang chạy. Xem thêm Debian Backports và tài liệu HTTP/3 của curl.

Gửi yêu cầu
curl -isS --ipv4 --max-time 10 --http3-only --cacert certs/server-chain.pem \
  https://localhost:8444/hello/Ada

Kết quả thực tế trên Raspberry Pi 5:

HTTP/3 200
content-type: text/plain; charset=utf-8

hello Ada

HTTP/3 200 xác nhận đúng phiên bản và yêu cầu đã thành công; hello Ada xác nhận yêu cầu đã tới đúng handler. --cacert giữ bước kiểm tra chứng chỉ; --ipv4 khớp địa chỉ lắng nghe 127.0.0.1. Nếu hết 10 giây mà chưa có phản hồi, kiểm tra bản curl và cổng UDP 8444; thêm -v để xem chi tiết kết nối.

Cấu hình theo ngôn ngữ · HTTP/2

Thay listener của first service; route và handler giữ nguyên.

Các khối dưới cấu hình HTTP/2 trên port 8443. Để làm Lab 03, đổi protocol sang HTTP/3 và port sang 8444. HTTP/1.1 dùng lại helper listen(...) của first service.

Ngôn ngữTên cần thêm vào import hiện có
GoKhông cần import mới; dùng alias coakkahttp đã có.
Kotlin/JavaListener, ListenerProtocol, TransportSecurity
PythonListener, ListenerProtocol, TransportSecurity từ coakka_http
Node.js/BunListenerProtocol, TransportSecurity từ đúng package của app host.
C/C++Các hằng số đã có trong <coakka/http/host.h>.
Gocoakka-http-runtime-go/v2 2.3.2 · listener struct tường minh.
Go · HTTP/2 listener
service, err := coakkahttp.NewBuilder().
    Listener(coakkahttp.Listener{
        BindAddress:          "127.0.0.1",
        Port:                 8443,
        Protocol:             coakkahttp.ProtocolHTTP2,
        Security:             coakkahttp.SecurityTLS,
        CredentialGeneration: 1,
        CredentialID:         "protocol-lab",
        CertificateChainFile: "certs/server-chain.pem",
        PrivateKeyFile:       "certs/server-key.pem",
    }).
    Get("/hello/{name}", func(request *coakkahttp.Request) (coakkahttp.Response, error) {
        name := request.PathParameters[0].EncodedValue
        return coakkahttp.Text(http.StatusOK, "hello "+name)
    }).
    Start()

Lab 03: ProtocolHTTP3 và port 8444.

Kotlin/JVMƯu tiên named parameters để thấy rõ ý nghĩa từng thuộc tính.
Kotlin · HTTP/2 listener
val service = ServiceBuilder()
    .listener(Listener(
        bindAddress = "127.0.0.1",
        port = 8443,
        protocol = ListenerProtocol.HTTP_2,
        security = TransportSecurity.TLS,
        credentialGeneration = 1,
        credentialId = "protocol-lab",
        certificateChainFile = "certs/server-chain.pem",
        privateKeyFile = "certs/server-key.pem",
    ))
    .get("/hello/{name}", Handler { request ->
        val name = request.pathParameters.first().encodedValue()
            .toString(Charsets.UTF_8)
        Responses.text("hello $name", status = 200)
    })
    .start()

Lab 03: ListenerProtocol.HTTP_3 và port 8444.

Java/JVMCùng artifact và native package với Kotlin.
Java · HTTP/2 listener
Listener listener = new Listener(
    "127.0.0.1", 8443,
    ListenerProtocol.HTTP_2,
    TransportSecurity.TLS,
    1L, "protocol-lab",
    "certs/server-chain.pem",
    "certs/server-key.pem",
    ""
);
Service service = new ServiceBuilder()
    .listener(listener)
    .get("/hello/{name}", request -> Responses.text(
        "hello " + new String(
            request.getPathParameters().get(0).encodedValue(),
            StandardCharsets.UTF_8),
        200))
    .start();

Lab 03: ListenerProtocol.HTTP_3 và port 8444.

PythonDataclass Listener giữ tên thuộc tính rõ ràng.
Python · HTTP/2 listener
service = (
    Builder()
    .listener(Listener(
        bind_address="127.0.0.1",
        port=8443,
        protocol=ListenerProtocol.HTTP_2,
        security=TransportSecurity.TLS,
        credential_generation=1,
        credential_id="protocol-lab",
        certificate_chain_file="certs/server-chain.pem",
        private_key_file="certs/server-key.pem",
    ))
    .get("/hello/{name}", hello)
    .start()
)

Lab 03: ListenerProtocol.HTTP_3 và port 8444.

Node.jsOfficial npm package coakka-http-runtime-node.
Node.js · HTTP/2 listener
const service = new Builder()
  .listener({
    host: "127.0.0.1",
    port: 8443,
    protocol: ListenerProtocol.HTTP_2,
    security: TransportSecurity.TLS,
    credentialGeneration: 1n,
    credentialId: "protocol-lab",
    certificateChainFile: "certs/server-chain.pem",
    privateKeyFile: "certs/server-key.pem",
  })
  .get("/hello/{name}", (request) => {
    const encodedName = request.pathParameters[0].encodedValue;
    const name = Buffer.from(encodedName).toString("utf8");
    return Response.text(`hello ${name}`, { status: 200 });
  })
  .start();

Lab 03: ListenerProtocol.HTTP_3 và port 8444.

BunOfficial npm-compatible package coakka-http-runtime-bun.
Bun · HTTP/2 listener
const service = new Builder()
  .listener({
    host: "127.0.0.1",
    port: 8443,
    protocol: ListenerProtocol.HTTP_2,
    security: TransportSecurity.TLS,
    credentialGeneration: 1n,
    credentialId: "protocol-lab",
    certificateChainFile: "certs/server-chain.pem",
    privateKeyFile: "certs/server-key.pem",
  })
  .get("/hello/{name}", (request) => {
    const encodedName = request.pathParameters[0].encodedValue;
    const name = Buffer.from(encodedName).toString("utf8");
    return Response.text(`hello ${name}`, { status: 200 });
  })
  .start();

Lab 03: ListenerProtocol.HTTP_3 và port 8444.

C/C++Public C ABI dùng chung cho C và C++.
Native · HTTP/2 configuration
coakka_http_host_configuration_t configuration;
coakka_http_host_configuration_init(&configuration);
configuration.bind_address = bytes("127.0.0.1");
configuration.port = 8443U;
configuration.protocol = COAKKA_HTTP_HOST_PROTOCOL_HTTP_2;
configuration.security = COAKKA_HTTP_HOST_SECURITY_TLS;
configuration.credential_generation = 1U;
configuration.credential_id = bytes("protocol-lab");
configuration.certificate_chain_file = bytes("certs/server-chain.pem");
configuration.private_key_file = bytes("certs/server-key.pem");

Lab 03: COAKKA_HTTP_HOST_PROTOCOL_HTTP_3 và port 8444U.

Giải thích tham số

Không copy cấu hình mà bỏ qua ý nghĩa.

Credential generation
1 là revision rõ ràng của bộ certificate/key trong bài. Nó không tự theo dõi file hoặc chứng minh reload.
Credential ID
Nhãn ổn định để nhận diện logical identity; không chứa secret.
Certificate chain
Public chain mà client kiểm tra. File tự ký của lab chỉ dành cho phát triển.
Private key
Phải khớp certificate, permission chặt và không xuất hiện trong log hoặc source control.
Trust roots
Để trống trong bài TLS một chiều. Chỉ thêm khi chuyển sang mTLS và cần xác thực client certificate.

Lab 04 · Advanced · MultiProtocol

Chạy HTTP/1.1, HTTP/2 và HTTP/3 trên cổng 8443

Tạo chứng chỉ thử nghiệm trong thư mục dự án. Chọn một ví dụ và dùng cùng listener cho 3 lần gửi bên dưới.

C# / .NETNuGet · .NET 8+ · 2.3.2

Tạo thư mục dự án riêng. Lưu 2 tệp sau, rồi chạy từ thư mục chứa certs/.

Server.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="CoAkka.Http.Runtime" Version="[2.3.2]" />
  </ItemGroup>
</Project>
Program.cs
using System.Text;
using CoAkka.Http;

if (args.Length == 0 || args[0] is not ("http1" or "http2" or "http3" or "multi") ||
    (args[0] == "http1" ? args.Length != 1 : args.Length != 2))
{
    Console.Error.WriteLine("Usage: Server http1 | Server <http2|http3|multi> <certificate-directory>");
    return 2;
}

const string address = "127.0.0.1";
const ulong helloBinding = 1;
string mode = args[0];
ushort port = mode == "http1" ? (ushort)8080 : (ushort)8443;
TlsOptions? tls = mode == "http1" ? null : new TlsOptions(
    "sample", 1, Path.Combine(args[1], "server-chain.pem"), Path.Combine(args[1], "server-key.pem"));
var listener = mode switch
{
    "multi" => HttpListenerOptions.MultiProtocolListener(tls!, bindAddress: address, port: port),
    "http2" => HttpListenerOptions.Standalone(HttpProtocol.Http2, bindAddress: address, port: port, tls: tls),
    "http3" => HttpListenerOptions.Standalone(HttpProtocol.Http3, bindAddress: address, port: port, tls: tls),
    _ => HttpListenerOptions.Standalone(HttpProtocol.Http11, bindAddress: address, port: port),
};

using var service = new HttpService(listener, [new HttpRoute(1, helloBinding, "GET", "/hello/Ada")]);
service.Start();
Console.WriteLine($"Listening on {(tls is null ? "http" : "https")}://{address}:{service.Port}/hello/Ada");

int remaining = mode == "multi" ? 3 : 1;
byte[] body = Encoding.UTF8.GetBytes("hello Ada");
HttpField[] headers = [new("content-type", "text/plain; charset=utf-8")];
while (remaining > 0)
{
    var request = service.Take(250);
    if (request is not { Kind: EventKind.Request, BindingId: helloBinding })
        continue;

    var status = service.Respond(request.Exchange, 200, body, headers);
    if (status == CoreStatus.StaleExchange)
        continue;
    if (status != CoreStatus.Ok)
        throw new InvalidOperationException($"Response refused: {status}");

    remaining--;
}

service.BeginDrain();
var drain = service.WaitDrained(5000);
service.Stop();
Console.WriteLine($"Drain: {drain.State} ({drain.Status})");
return drain.State == DrainState.Complete ? 0 : 1;
Terminal
dotnet run --project Server.csproj -- multi certs

Chạy riêng từng giao thức hoặc gửi 3 yêu cầu trên cùng một cổng.

SwiftSwiftPM · Swift 6.0+ · 2.3.2

Tạo thư mục dự án riêng. Lưu 2 tệp sau, rồi chạy từ thư mục chứa certs/.

Lệnh bên dưới dùng macOS ARM64 từ macOS 14. Trên Linux và Windows, đặt thư viện native cạnh executable theo hướng dẫn cài SwiftPM.

Package.swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "CoAkkaHttpListenerSample",
    platforms: [.macOS(.v14)],
    dependencies: [
        .package(url: "https://github.com/phuong-tran/coakka-http-runtime-swift.git", exact: "2.3.2"),
    ],
    targets: [
        .executableTarget(name: "Server", dependencies: [
            .product(name: "CoAkkaHttp", package: "coakka-http-runtime-swift"),
        ]),
    ]
)
Sources/Server/main.swift
import CoAkkaHttp
import Foundation

enum SampleError: Error {
    case usage(String)
    case responseRefused(CoreStatus)
    case drainFailed(DrainState, CoreStatus)
}

let args = Array(CommandLine.arguments.dropFirst())
guard let mode = args.first, ["http1", "http2", "http3", "multi"].contains(mode),
      args.count == (mode == "http1" ? 1 : 2) else {
    throw SampleError.usage("Usage: Server http1 | Server <http2|http3|multi> <certificate-directory>")
}

let address = "127.0.0.1"
let port: UInt16 = mode == "http1" ? 8080 : 8443
let listener: HttpListener
if mode == "http1" {
    listener = .standalone(protocol: .http11, address: address, port: port)
} else {
    let certificates = URL(fileURLWithPath: args[1], isDirectory: true)
    let tls = TlsOptions(
        credentialID: "sample", generation: 1,
        certificateChainFile: certificates.appendingPathComponent("server-chain.pem").path,
        privateKeyFile: certificates.appendingPathComponent("server-key.pem").path)
    switch mode {
    case "multi": listener = .multiProtocolListener(tls: tls, address: address, port: port)
    case "http2": listener = .standalone(protocol: .http2, address: address, port: port, tls: tls)
    default: listener = .standalone(protocol: .http3, address: address, port: port, tls: tls)
    }
}

let helloBinding: UInt64 = 1
let route = HttpRoute(routeID: 1, bindingID: helloBinding, method: "GET", pattern: "/hello/Ada")
let service = try HttpService(listener: listener, routes: [route])
defer { try? service.close() }
try service.start()
let scheme = mode == "http1" ? "http" : "https"
print("Listening on \(scheme)://\(address):\(try service.port)/hello/Ada")

var remaining = mode == "multi" ? 3 : 1
let body = Array("hello Ada".utf8)
let headers = [HttpField("content-type", "text/plain; charset=utf-8")]
while remaining > 0 {
    guard let request = try service.take(timeoutMilliseconds: 250),
          request.kind == .request, request.bindingID == helloBinding else { continue }

    let status = try service.respond(to: request.exchange, status: 200, body: body, headers: headers)
    if status == .staleExchange { continue }
    guard status == .ok else { throw SampleError.responseRefused(status) }
    remaining -= 1
}

try service.beginDrain()
let drain = try service.waitDrained(timeoutMilliseconds: 5000)
try service.stop()
guard drain.state == .complete, drain.status == .ok else {
    throw SampleError.drainFailed(drain.state, drain.status)
}
try service.close()
print("Drain: Complete (Ok)")
Terminal
swift run Server multi certs

Chạy riêng từng giao thức hoặc gửi 3 yêu cầu trên cùng một cổng.

Chạy riêng từng giao thức bằng C# hoặc Swift

Thay multi certs trong lệnh mở server bằng đối số của giao thức muốn thử. Mở terminal thứ hai trong cùng thư mục dự án để chạy lệnh curl tương ứng.

HTTPĐối số của serverLệnh kiểm tra
HTTP/1.1http1curl -isS --http1.1 http://127.0.0.1:8080/hello/Ada
HTTP/2http2 certscurl -isS --http2 --cacert certs/server-chain.pem https://127.0.0.1:8443/hello/Ada
HTTP/3http3 certscurl -isS --http3-only --cacert certs/server-chain.pem https://127.0.0.1:8443/hello/Ada

Kết quả đúng hiện phiên bản HTTP tương ứng, mã 200 và nội dung hello Ada. Server in Drain: Complete (Ok) rồi thoát sau 1 yêu cầu ở chế độ riêng hoặc 3 yêu cầu với MultiProtocol. Nếu curl chưa có HTTP/3, xem cách cài bản có hỗ trợ trên Raspberry Pi.

C/C++ · SDK 2.3.0Dùng api.create() của Listener V1; SDK mở TCP và UDP trên cùng cổng.

Trên Linux hoặc macOS, tải SDK 2.3.0 đúng nền tảng và mã kiểm tra SHA-256. Đặt COAKKA_HTTP_SDK thành đường dẫn tuyệt đối tới thư mục SDK đã giải nén. Lưu 5 tệp theo đúng tên bên dưới vào thư mục dự án, cùng cấp với thư mục certs/. C và C++ dùng chung mã listener; main.cpp còn tự đóng dịch vụ khi đối tượng ra khỏi phạm vi.

1 · Tệp dùng chung
CMakeLists.txt
cmake_minimum_required(VERSION 3.24)
project(coakka_same_port_lab LANGUAGES C CXX)

find_package(CoAkkaHttpHost 2.3.0 EXACT CONFIG REQUIRED)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED YES)
set(CMAKE_C_EXTENSIONS NO)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
set(CMAKE_CXX_EXTENSIONS NO)

add_library(lab-listener STATIC listener.c)
target_link_libraries(lab-listener PUBLIC CoAkkaHttp::host)

add_executable(same-port-c main.c)
target_link_libraries(same-port-c PRIVATE lab-listener)

add_executable(same-port-cpp main.cpp)
target_link_libraries(same-port-cpp PRIVATE lab-listener)

foreach(target IN ITEMS lab-listener same-port-c same-port-cpp)
  if(MSVC)
    target_compile_options(${target} PRIVATE /W4 /WX)
  else()
    target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror)
  endif()
endforeach()
listener.h
#ifndef COAKKA_PORTAL_SAME_PORT_LISTENER_H
#define COAKKA_PORTAL_SAME_PORT_LISTENER_H

#include <coakka/http/host.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Open can leave a created owner even if startup fails. Always close it. */
bool lab_open(coakka_http_host_service_t **service);
bool lab_serve(coakka_http_host_service_t *service);
bool lab_close(coakka_http_host_service_t **service);

#ifdef __cplusplus
}
#endif

#endif
listener.c
#include "listener.h"

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

enum { LAB_PORT = 8443, LAB_REQUESTS = 3 };

static coakka_http_host_bytes_t bytes(const char *text) {
  const coakka_http_host_bytes_t span = {
      .data = (const uint8_t *)text,
      .size = strlen(text),
  };
  return span;
}

static bool check(coakka_http_host_status_t status, const char *operation) {
  if (status == COAKKA_HTTP_HOST_OK) {
    return true;
  }
  fprintf(stderr, "%s: %s\n", operation, coakka_http_host_status_name(status));
  return false;
}

bool lab_open(coakka_http_host_service_t **service) {
  if (coakka_http_host_abi_version() != 10U) {
    fputs("This lab requires Core ABI 10.\n", stderr);
    return false;
  }
  coakka_http_host_multi_listener_api_v1_t api = {.struct_size = sizeof(api)};
  if (!check(coakka_http_host_multi_listener_get_api_v1(&api),
             "get Listener V1")) {
    return false;
  }
  if ((api.supported_profiles &
       COAKKA_HTTP_HOST_MULTI_LISTENER_HTTPS_ALL_THREE) == 0U) {
    fputs("The loaded SDK does not offer the all-three HTTPS profile.\n",
          stderr);
    return false;
  }

  coakka_http_host_configuration_t configuration;
  coakka_http_host_configuration_init(&configuration);
  configuration.bind_address = bytes("127.0.0.1");
  configuration.port = LAB_PORT;
  configuration.security = COAKKA_HTTP_HOST_SECURITY_TLS;
  configuration.credential_generation = 1U;
  configuration.credential_id = bytes("portal-lab");
  configuration.certificate_chain_file = bytes("certs/server-chain.pem");
  configuration.private_key_file = bytes("certs/server-key.pem");

  coakka_http_host_route_t route;
  coakka_http_host_route_init(&route);
  route.route_id = 1U;
  route.handler_binding_id = 1U;
  route.method = bytes("GET");
  route.encoded_path_pattern = bytes("/hello/Ada");

  /* The V1 constructor selects all three. Do not assign configuration.protocol.
   */
  uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
  if (!check(api.create(&configuration, &route, 1U, service, &failed_route),
             "create Listener V1")) {
    if (failed_route != COAKKA_HTTP_HOST_FAILED_INDEX_NONE) {
      fprintf(stderr, "Invalid route at index %" PRIu32 "\n", failed_route);
    }
    return false;
  }

  coakka_http_host_issue_t issue;
  coakka_http_host_issue_init(&issue);
  coakka_http_host_multi_listener_info_v1_t info = {.struct_size =
                                                        sizeof(info)};
  if (!check(coakka_http_host_service_start(*service, &issue),
             "start service")) {
    if (check(api.inspect(*service, &info), "inspect failed startup")) {
      fprintf(stderr, "Startup phase=%" PRIu32 ", transport=%" PRIu32 "\n",
              info.start_failure_phase, info.start_failure_transport);
    }
    return false;
  }
  if (!check(api.inspect(*service, &info), "inspect running listener")) {
    return false;
  }
  const uint32_t all_protocols = COAKKA_HTTP_HOST_MULTI_LISTENER_HTTP_1_1 |
                                 COAKKA_HTTP_HOST_MULTI_LISTENER_HTTP_2 |
                                 COAKKA_HTTP_HOST_MULTI_LISTENER_HTTP_3;
  const uint32_t both_transports =
      COAKKA_HTTP_HOST_MULTI_LISTENER_TCP | COAKKA_HTTP_HOST_MULTI_LISTENER_UDP;
  if (info.lifecycle != COAKKA_HTTP_HOST_MULTI_LISTENER_RUNNING ||
      info.port != LAB_PORT || info.admitting_protocols != all_protocols ||
      info.bound_transports != both_transports) {
    fputs("Core did not admit all three protocols on the requested port.\n",
          stderr);
    return false;
  }
  printf("https://127.0.0.1:%u/hello/Ada\n", (unsigned)info.port);
  puts("Listening on TCP and UDP; send three requests to finish the lab.");
  fflush(stdout);
  return true;
}

static bool same_exchange(coakka_http_host_exchange_t a,
                          coakka_http_host_exchange_t b) {
  return a.slot == b.slot && a.generation == b.generation;
}

bool lab_serve(coakka_http_host_service_t *service) {
  coakka_http_host_exchange_t pending[LAB_REQUESTS];
  size_t pending_count = 0U;
  unsigned submitted = 0U;
  unsigned finished = 0U;
  while (finished < LAB_REQUESTS) {
    coakka_http_host_request_event_t event;
    coakka_http_host_request_event_init(&event);
    if (!check(coakka_http_host_take_request(service, 60000U, &event),
               "wait for a lab request or completion")) {
      return false;
    }

    /* Copy identity before releasing the event; no borrowed bytes are retained.
     */
    const coakka_http_host_request_event_kind_t kind = event.kind;
    const coakka_http_host_exchange_t exchange = event.exchange;
    if (!check(coakka_http_host_release_request(service, &event),
               "release event")) {
      return false;
    }

    if (kind == COAKKA_HTTP_HOST_REQUEST && submitted < LAB_REQUESTS) {
      coakka_http_host_response_t response;
      coakka_http_host_response_init(&response);
      response.status_code = 200U;
      response.body = bytes("hello Ada");
      if (!check(coakka_http_host_respond(service, exchange, &response),
                 "submit response")) {
        return false;
      }
      pending[pending_count++] = exchange;
      ++submitted;
    } else if (kind == COAKKA_HTTP_HOST_REQUEST_TERMINAL) {
      size_t index = 0U;
      while (index < pending_count &&
             !same_exchange(pending[index], exchange)) {
        ++index;
      }
      if (index == pending_count) {
        fputs("Received a completion for an unexpected request.\n", stderr);
        return false;
      }
      pending[index] = pending[--pending_count];
      ++finished;
    } else {
      fputs("This lab expects exactly three buffered requests.\n", stderr);
      return false;
    }
  }

  coakka_http_host_drain_state_t state = COAKKA_HTTP_HOST_DRAIN_NOT_STARTED;
  if (!check(coakka_http_host_service_begin_drain(service), "begin drain") ||
      !check(coakka_http_host_service_wait_drained(service, 5000U, &state),
             "wait for drain") ||
      state != COAKKA_HTTP_HOST_DRAIN_COMPLETE) {
    return false;
  }
  puts("Three request completions observed; drain complete.");
  return true;
}

bool lab_close(coakka_http_host_service_t **service) {
  if (*service == NULL) {
    return true;
  }
  const bool stopped =
      check(coakka_http_host_service_stop(*service), "stop service");
  const bool destroyed =
      check(coakka_http_host_service_destroy(service), "destroy service");
  return stopped && destroyed;
}
2 · Điểm chạy C
main.c
#include "listener.h"

#include <stdlib.h>

int main(void) {
  coakka_http_host_service_t *service = NULL;
  const bool served = lab_open(&service) && lab_serve(service);
  const bool closed = lab_close(&service);
  return served && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
3 · Điểm chạy C++
main.cpp
#include "listener.h"

#include <cstdlib>

class Service final {
public:
  Service() = default;
  Service(const Service &) = delete;
  Service &operator=(const Service &) = delete;
  ~Service() { (void)close(); }

  bool open() { return lab_open(&service_); }
  bool serve() { return lab_serve(service_); }
  bool close() { return lab_close(&service_); }

private:
  coakka_http_host_service_t *service_ = nullptr;
};

int main() {
  Service service;
  const bool served = service.open() && service.serve();
  // Check close explicitly so a cleanup failure reaches the exit status.
  const bool closed = service.close();
  return served && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}

Build một lần, rồi chọn chạy C hoặc C++. Chờ chương trình đầu tiên thoát trước khi chạy bản còn lại vì cả hai cùng dùng cổng 8443.

CMake
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build --config Release
C
./build/same-port-c
C++
./build/same-port-cpp

Khi chương trình in URL, chạy 3 lệnh curl bên dưới. Chương trình chờ tối đa 60 giây cho sự kiện tiếp theo và tự thoát sau khi cả 3 yêu cầu hoàn tất. Terminal của chương trình in Three request completions observed; drain complete.. Nếu không khởi động được, kiểm tra 2 file chứng chỉ và xem TCP lẫn UDP ở cổng 8443 còn trống không.

Ví dụ đầy đủ · listener.mjs
Ví dụ đầy đủ · listener.mjs
import { resolve } from "node:path";

const connector = process.versions.bun
  ? "coakka-http-runtime-bun"
  : "coakka-http-runtime-node";
const { Builder, ListenerProtocol, Response, TransportSecurity } = await import(connector);

const [mode] = process.argv.slice(2);
if (!["http1", "http2", "http3", "multi"].includes(mode)) {
  throw new Error("Choose http1, http2, http3 or multi.");
}

const builder = new Builder();
if (mode === "http1") {
  builder.listen("127.0.0.1", 8080);
} else {
  const tls = {
    host: "127.0.0.1",
    port: mode === "http3" ? 8444 : 8443,
    credentialId: "portal-lab",
    credentialGeneration: 1n,
    certificateChainFile: resolve("certs/server-chain.pem"),
    privateKeyFile: resolve("certs/server-key.pem"),
  };
  if (mode === "multi") {
    builder.multiProtocolListener(tls);
  } else {
    builder.listener({
      ...tls,
      protocol: mode === "http2" ? ListenerProtocol.HTTP_2 : ListenerProtocol.HTTP_3,
      security: TransportSecurity.TLS,
    });
  }
}

const stopped = new Promise((done) => {
  process.once("SIGINT", done);
  process.once("SIGTERM", done);
});
const service = builder.get("/hello/Ada", () => Response.text("hello Ada")).start();

try {
  const scheme = mode === "http1" ? "http" : "https";
  console.log(`${scheme}://127.0.0.1:${service.port}/hello/Ada`);
  if (mode === "multi") console.log(service.listenerInfo());
  await stopped;
} finally {
  await service.close();
}
Node.js · npm
Node.js · npm
npm install --save-exact [email protected]
node listener.mjs multi
Bun
Bun
bun add --exact [email protected]
bun listener.mjs multi

Để làm lại bài 01–03 với cùng file, chạy từng chế độ: http1 ở cổng 8080, http2 ở 8443 hoặc http3 ở 8444. Nhấn Ctrl+C để đóng dịch vụ trước khi đổi chế độ.

Trong terminal thứ hai, gửi cả 3 yêu cầu tới cùng URL HTTPS. Bài chỉ đạt khi cả 3 trả hello Ada và phiên bản quan sát lần lượt là 1.1, 2 và 3.

Terminal
(
  for protocol in --http1.1 --http2 --http3-only; do
    curl --noproxy '*' "$protocol" --cacert certs/server-chain.pem \
      --fail --silent --show-error --max-time 10 \
      --write-out '\n%{http_code} %{http_version}\n' \
      https://127.0.0.1:8443/hello/Ada || exit 1
  done
)
hello Ada
200 1.1
hello Ada
200 2
hello Ada
200 3

Đã chạy trên Raspberry Pi 5 với C và C++ (SDK 2.2.0), Node.js và Bun (connector 2.2.1), dùng curl 8.14.1 của Debian. api.inspect() trong C/C++ hoặc listenerInfo() trong Node.js/Bun cho biết listener đang nhận giao thức nào. Curl cho biết mỗi yêu cầu thực sự dùng phiên bản nào.

Các bài C/C++, Node.js và Bun đã chạy lại trên Mac ARM64 với Core SDK 2.3.0 và connector 2.3.1. Lượt này dùng curl cho HTTP/1.1 và HTTP/2, aioquic cho HTTP/3.

Nếu chỉ HTTP/3 lỗi, kiểm tra curl có hỗ trợ HTTP/3 và UDP 8443 có tới được dịch vụ không. TCP 8443 tới được chỉ xác nhận đường đi cho HTTP/1.1 và HTTP/2.

Bài tùy chọn · chỉ sau 3 bài riêng

So sánh mà không biến một lần chạy thành benchmark.

Chạy cùng route và payload trên ba endpoint, ghi protocol thực tế, TCP/UDP, TLS, status, body và failure. Một vài request trên laptop chỉ chứng minh cấu hình và wire path; không chứng minh phiên bản nào nhanh hơn trong production.

EndpointClient ép versionEvidence cần ghi
:8080 TCP--http1.1HTTP/1.1 + status/body
:8443 TCP + TLS--http2ALPN h2 + HTTP/2 + status/body
:8444 UDP + TLS 1.3--http3-onlyHTTP/3 + status/body

Failure + Monitor

Kiểm tra từ cấu hình đã được chấp nhận tới request thật.