Cấu hình
Dùng helper listen("127.0.0.1", 8080), hoặc listener có protocol HTTP/1.1 và security plaintext.
Study · Advanced · 3 bài riêng + 1 bài cùng cổ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
/hello/{name}; chỉ thay cách khai báo listener.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
Dùng helper listen("127.0.0.1", 8080), hoặc listener có protocol HTTP/1.1 và security plaintext.
Giữ service chạy và xác nhận nó in đúng endpoint loopback.
curl -i --max-time 10 --http1.1 http://127.0.0.1:8080/hello/AdaHTTP/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
localhost.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
h2.8443.http://.ALPN: server accepted h2, sau đó kiểm tra HTTP/2 200 và nội dung hello Ada.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
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.8444. Bài chạy cùng máy qua 127.0.0.1; không cần mở cổng ra ngoài.--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.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:
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/nullsudo apt update
sudo apt install -t trixie-backports curl
/usr/bin/curl --versionSau 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.
curl -isS --ipv4 --max-time 10 --http3-only --cacert certs/server-chain.pem \
https://localhost:8444/hello/AdaKế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
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ó |
|---|---|
| Go | Không cần import mới; dùng alias coakkahttp đã có. |
| Kotlin/Java | Listener, ListenerProtocol, TransportSecurity |
| Python | Listener, ListenerProtocol, TransportSecurity từ coakka_http |
| Node.js/Bun | ListenerProtocol, TransportSecurity từ đúng package của app host. |
| C/C++ | Các hằng số đã có trong <coakka/http/host.h>. |
coakka-http-runtime-go/v2 2.3.2 · listener struct tường minh.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.
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.
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.
Listener giữ tên thuộc tính rõ ràng.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.
coakka-http-runtime-node.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.
coakka-http-runtime-bun.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.
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ố
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.Lab 04 · Advanced · MultiProtocol
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.
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/.
<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>
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;
dotnet run --project Server.csproj -- multi certsChạ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.
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.
// 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"),
]),
]
)
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)")
swift run Server multi certsChạ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.
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 server | Lệnh kiểm tra |
|---|---|---|
| HTTP/1.1 | http1 | curl -isS --http1.1 http://127.0.0.1:8080/hello/Ada |
| HTTP/2 | http2 certs | curl -isS --http2 --cacert certs/server-chain.pem https://127.0.0.1:8443/hello/Ada |
| HTTP/3 | http3 certs | curl -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.
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.
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()
#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
#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;
}
#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;
}
#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 -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build --config Release./build/same-port-c./build/same-port-cppKhi 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.
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();
}
npm install --save-exact [email protected]
node listener.mjs multibun 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.
(
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
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.
| Endpoint | Client ép version | Evidence cần ghi |
|---|---|---|
:8080 TCP | --http1.1 | HTTP/1.1 + status/body |
:8443 TCP + TLS | --http2 | ALPN h2 + HTTP/2 + status/body |
:8444 UDP + TLS 1.3 | --http3-only | HTTP/3 + status/body |
Failure + Monitor