Configure
Use listen("127.0.0.1", 8080), or an explicit HTTP/1.1 plaintext listener.
Study · Advanced · 3 focused labs + one shared port
Keep the GET /hello/Ada route from the
first-service lesson. Each lab changes only the listener, port
exposure and verification command, so HTTP/1.1, HTTP/2 and HTTP/3
outcomes never blur together.
Prepare once
/hello/{name} route and handler; replace only the listener declaration.Run the service in one terminal and send requests from a second
terminal on the same machine. Start both in the project directory
containing certs/. Stop the service after each lab as
shown in its language Study.
Prefer one complete example? Use the Node.js/Bun file in http1, http2 or http3 mode.
The current examples pin 2.3.2 and use Core SDK 2.3.0.
For C/C++: the first service serves /hello
and returns hello native. Use /hello instead
of /hello/Ada in all 3 curl commands and check the same
protocol and status. In Lab 01, set configuration.port = 8080U.
Lab 01 · Beginner baseline · HTTP/1.1
Use listen("127.0.0.1", 8080), or an explicit HTTP/1.1 plaintext listener.
Keep it running and confirm the printed loopback endpoint.
curl -i --max-time 10 --http1.1 http://127.0.0.1:8080/hello/AdaHTTP/1.1 200 OK
...
hello AdaPass: status is 200, the body matches and the service reports no failure. This lab does not prove TLS, HTTP/2 or HTTP/3.
Prepare for Labs 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 is a private key; never commit or log it. Pass server-chain.pem to curl --cacert so the lab still verifies trust. Do not use -k.
Lab 02 · Advanced · HTTP/2
h2.8443.http://.ALPN: server accepted h2, then check for HTTP/2 200 and hello Ada.curl -isSv --ipv4 --max-time 10 --http2 --cacert certs/server-chain.pem \
https://localhost:8443/hello/AdaPass: the client negotiates h2. ALPN is
the TLS-handshake line showing which version both sides agreed to use.
The client receives 200 and hello Ada. If curl lacks HTTP/2,
change the client rather than declaring the service broken.
Lab 03 · Advanced · HTTP/3
curl --version. If Features lists HTTP3, try the installed curl. Debian 13 users can use Backports when they need a different build.8444. This lab runs on the same machine via 127.0.0.1; no external port needs to be opened.--http3-only. If HTTP/3 fails, curl reports an error instead of falling back to HTTP/2 or HTTP/1.1.Check that /etc/os-release shows VERSION_CODENAME=trixie
and dpkg --print-architecture prints arm64.
If trixie-backports is not enabled, add the official repository once:
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 --versionCheck that Features includes HTTP3 after installation. On the test Pi, the stock Debian curl 8.14.1 passed against 2.2.1, so Backports was not required. Curl 8.21.0 from Backports also passed HTTP/3 on both the standalone and shared port.
On Debian 12 (Bookworm) or another operating system, use a package for that system. See Debian Backports and curl's HTTP/3 guide.
curl -isS --ipv4 --max-time 10 --http3-only --cacert certs/server-chain.pem \
https://localhost:8444/hello/AdaObserved on Raspberry Pi 5:
HTTP/3 200
content-type: text/plain; charset=utf-8
hello Ada
HTTP/3 200 confirms the protocol and successful request;
hello Ada confirms the request reached the expected handler.
--cacert keeps certificate verification enabled, and
--ipv4 matches the 127.0.0.1 listener. If
there is no response after 10 seconds, check the curl build and UDP
port 8444. Add -v for connection details.
Language configuration · HTTP/2
Each block configures HTTP/2 on port 8443. For Lab 03, select HTTP/3 and port 8444. HTTP/1.1 uses the original listen(...) helper.
| Language | Names to add to the existing import |
|---|---|
| Go | No new import; reuse the existing coakkahttp alias. |
| Kotlin/Java | Listener, ListenerProtocol, TransportSecurity |
| Python | Listener, ListenerProtocol, TransportSecurity from coakka_http |
| Node.js/Bun | ListenerProtocol, TransportSecurity from the correct app-host package. |
| C/C++ | The constants already come from <coakka/http/host.h>. |
coakka-http-runtime-go/v2 2.3.2 · explicit listener struct.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: use ProtocolHTTP3 and 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: use ListenerProtocol.HTTP_3 and 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: use ListenerProtocol.HTTP_3 and port 8444.
Listener dataclass keeps property names visible.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: use ListenerProtocol.HTTP_3 and 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: use ListenerProtocol.HTTP_3 and 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: use ListenerProtocol.HTTP_3 and 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: use COAKKA_HTTP_HOST_PROTOCOL_HTTP_3 and port 8444U.
Parameter meaning
1 is an explicit revision for this lab's certificate and key. It does not watch files or prove reload.Lab 04 · Advanced · MultiProtocol
Create the development certificate in the project directory. Choose one example and keep the listener for all 3 requests below.
Create a project directory. Save these two files and run from the directory containing 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 certsRun one protocol at a time or send 3 requests on the shared port.
Create a project directory. Save these two files and run from the directory containing certs/.
The command below uses macOS 14 or later on ARM64. On Linux and Windows, place the native libraries beside the executable using the SwiftPM platform setup.
// 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 certsRun one protocol at a time or send 3 requests on the shared port.
Replace multi certs in the server command with the arguments for the protocol you want to try. Run the matching curl command from a second terminal in the same project directory.
| HTTP | Server arguments | Check in another terminal |
|---|---|---|
| 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 |
Expect the matching HTTP version, status 200 and body hello Ada. The server prints Drain: Complete (Ok) and exits after 1 standalone request or 3 MultiProtocol requests. If curl lacks HTTP/3, see how to get a build that supports it on Raspberry Pi.
api.create() for Listener V1; the SDK opens TCP and UDP on the same port.On Linux or macOS, download the matching SDK 2.3.0 and its SHA-256 checksums. Set COAKKA_HTTP_SDK to the absolute extracted SDK path. Save all 5 files in the project directory, alongside the certs/ folder. C and C++ share the same listener code; main.cpp also closes the service when its owner goes out of scope.
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 once, then run either C or C++. Wait until the first program exits before trying the other; both use port 8443.
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build --config Release./build/same-port-c./build/same-port-cppRun the 3 curl checks below as soon as the URL appears. The native program waits up to 60 seconds for the next event and exits after all 3 requests finish. Look for Three request completions observed; drain complete. in its terminal. If startup fails, check the certificate files and make sure TCP and UDP port 8443 are free.
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 multiTo repeat Labs 01–03 with the same file, launch one mode at a time: http1 on 8080, http2 on 8443 or http3 on 8444. Stop each service with Ctrl+C before starting the next.
In another terminal, run all 3 requests against the same HTTPS URL. Pass only if the body is hello Ada each time and the negotiated versions are 1.1, 2 and 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
Verified on Raspberry Pi 5 with C and C++ (SDK 2.2.0), Node.js and Bun (connectors 2.2.1), and Debian curl 8.14.1. api.inspect() in C/C++ or listenerInfo() in Node.js/Bun reports which protocols the listener accepts. Curl shows the version each request actually used.
The C/C++, Node.js and Bun labs were replayed on Mac ARM64 with Core SDK 2.3.0 and connectors 2.3.1. The Mac checks used curl for HTTP/1.1 and HTTP/2 and aioquic for HTTP/3.
If only HTTP/3 fails, check that curl has HTTP/3 and that UDP 8443 reaches the server. TCP 8443 reaching the server only proves HTTP/1.1 and HTTP/2 can get there.
Optional exercise · after 3 focused labs + one shared port
Run the same route and payload on three endpoints, recording the observed protocol, TCP/UDP, TLS, status, body and failure. A few laptop requests prove configuration and wire path, not which version is faster in production.
| Endpoint | Forced client version | Evidence |
|---|---|---|
: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