Study · NuGet · 2.3.2

Learn CoAkka HTTP Runtime with C#

Start with one request in one process. Then send a file, stream updates, open a WebSocket and watch the service finish its work.

Beginner

Install the connector

Use .NET SDK 8 or later and create a project folder. The manifest pins CoAkka.Http.Runtime 2.3.2 from NuGet.

Terminal
dotnet --version
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>

In 2.3.2, 2.3 identifies Core and 2 is the connector revision. The package includes the matching native libraries.

Beginner

Serve the first request

Save this file as Program.cs.

Program.cs
using CoAkka.Http;
using System.Text;

HttpListenerOptions listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
var route = new HttpRoute(RouteId: 1, BindingId: 1, Method: "GET", Pattern: "/hello/{name}");
using var service = new HttpService(listener, routes: [route]);
service.Start();
Console.WriteLine($"http://127.0.0.1:{service.Port}/hello/Ada");

var waitStarted = System.Diagnostics.Stopwatch.StartNew();
var request = service.Take(timeoutMilliseconds: 250);
while (request is null && waitStarted.Elapsed < TimeSpan.FromMinutes(1))
{
    request = service.Take(timeoutMilliseconds: 250);
}
if (request is not { Kind: EventKind.Request, BindingId: 1 })
{
    throw new TimeoutException("No matching request arrived.");
}
string name = request.PathParameters.Single(field => field.Name == "name").Value ?? "";
RequireOk(service.Respond(
    exchange: request.Exchange, status: 200, body: Encoding.UTF8.GetBytes($"hello {name}"),
    headers: [new HttpField("content-type", "text/plain; charset=utf-8")]));

service.BeginDrain();
var drain = service.WaitDrained(timeoutMilliseconds: 5000);
service.Stop();
if (drain.State != DrainState.Complete || drain.Status != CoreStatus.Ok)
{
    throw new InvalidOperationException($"Drain ended with {drain.State} ({drain.Status}).");
}
Console.WriteLine("drain complete");

static void RequireOk(CoreStatus status)
{
    if (status != CoreStatus.Ok)
    {
        throw new InvalidOperationException($"Core refused the operation: {status}.");
    }
}
Terminal
dotnet run --project Server.csproj

When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.

Terminal
curl -isS "$BASE_URL/hello/Ada"

Expect 200 and hello Ada. The server serves one matching request, drains and exits. A port of 0 lets the OS pick a free port.

Beginner

Read the request

Restart the first example and call /hello/Ada?tag=one&tag=two&flag. It still returns hello Ada. Inspect the request in the debugger to see the 3 ordered query entries.

PathParameters
The capture name from /hello/{name}. Decode and validate it when needed.
QueryParameters
Entries keep order, duplicate keys and the difference between a missing and an empty value.
Headers
Read each value your handler needs. The Core already matched the method and path.
Body
The buffered request body. Use a streaming route when the body needs incremental processing.

Request anatomy

Beginner

Call an upstream service

In a separate terminal, start an HTTP/1.1 upstream with Python 3.11+.

Terminal
mkdir -p upstream
printf '%s\n' 'hello upstream' > upstream/hello.txt
python3 -m http.server 9080 --bind 127.0.0.1 --protocol HTTP/1.1 --directory upstream

Save this file as Program.cs, replacing the previous episode’s source.

Program.cs
using CoAkka.Http;
using System.Text;

var listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
var endpoint = new OutboundEndpoint(
    NodeId: "local", ConnectHost: "127.0.0.1", ConnectPort: 9080,
    HttpAuthority: "127.0.0.1:9080");
var target = new OutboundTarget(Name: "example", Generation: 1, Endpoints: [endpoint]);
using var service = new HttpService(
    listener, routes: [], staticMounts: [], fileAuthorities: [], monitor: null,
    outbound: new OutboundOptions(Targets: [target]));
service.Start();

var call = service.SubmitOutbound(new OutboundRequest(
    LogicalTarget: "example", Method: "GET", Target: "/hello.txt", TimeoutMilliseconds: 3000));
var result = service.TakeOutbound(timeoutMilliseconds: 5000);
if (result is null || !result.Call.Equals(call))
{
    throw new InvalidOperationException("The call's terminal result is missing.");
}
if (result.Reason != OutboundReason.Response || result.ResponseStatus != 200)
{
    throw new InvalidOperationException($"Upstream returned {result.Reason} ({result.ResponseStatus}).");
}
Console.WriteLine($"HTTP {result.ResponseStatus}");
Console.WriteLine(Encoding.UTF8.GetString(result.Body));
service.Stop();
Terminal
dotnet run --project Server.csproj

Expect HTTP 200 then hello upstream. The 3-second request deadline and the 5-second result wait serve separate purposes. Stop the fixture with Ctrl+C when done.

Read outbound failures

Advanced

Send a file

Create one test file. The file authority confines the handler’s selection to this directory and bounds active files and size.

Terminal
mkdir -p files
printf '%s\n' 'CoAkka file delivery' > files/manual.txt

Save this file as Program.cs, replacing the previous episode’s source.

Program.cs
using CoAkka.Http;

HttpListenerOptions listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
string root = Path.GetFullPath("files");
var files = new FileAuthority(Id: 1, Root: root, MaxActiveFiles: 4, MaxFileBytes: 1024 * 1024);
var route = new HttpRoute(RouteId: 1, BindingId: 1, Method: "GET", Pattern: "/download");
using var service = new HttpService(listener, routes: [route], staticMounts: [], fileAuthorities: [files], monitor: null);
service.Start();
Console.WriteLine($"http://127.0.0.1:{service.Port}/download");

var waitStarted = System.Diagnostics.Stopwatch.StartNew();
var request = service.Take(timeoutMilliseconds: 250);
while (request is null && waitStarted.Elapsed < TimeSpan.FromMinutes(1))
{
    request = service.Take(timeoutMilliseconds: 250);
}
if (request is not { Kind: EventKind.Request, BindingId: 1 })
{
    throw new TimeoutException("No matching request arrived.");
}
RequireOk(service.RespondFile(
    exchange: request.Exchange, status: 200, authorityId: files.Id, encodedPath: "/manual.txt"));

service.BeginDrain();
var drain = service.WaitDrained(timeoutMilliseconds: 5000);
service.Stop();
if (drain.State != DrainState.Complete || drain.Status != CoreStatus.Ok)
{
    throw new InvalidOperationException($"Drain ended with {drain.State} ({drain.Status}).");
}
Console.WriteLine("drain complete");

static void RequireOk(CoreStatus status)
{
    if (status != CoreStatus.Ok)
    {
        throw new InvalidOperationException($"Core refused the operation: {status}.");
    }
}
Terminal
dotnet run --project Server.csproj

When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.

Terminal
curl -isS "$BASE_URL/download"

Expect the contents of files/manual.txt. This example sends a file from the server to the client. See the file delivery guide. For the reverse direction, open the upload labs.

Advanced

Send two server events

Save this file as Program.cs, replacing the previous episode’s source.

Program.cs
using CoAkka.Http;

HttpListenerOptions listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
var route = new HttpRoute(RouteId: 1, BindingId: 1, Method: "GET", Pattern: "/events");
using var service = new HttpService(listener, routes: [route]);
service.Start();
Console.WriteLine($"http://127.0.0.1:{service.Port}/events");

var waitStarted = System.Diagnostics.Stopwatch.StartNew();
var request = service.Take(timeoutMilliseconds: 250);
while (request is null && waitStarted.Elapsed < TimeSpan.FromMinutes(1))
{
    request = service.Take(timeoutMilliseconds: 250);
}
if (request is not { Kind: EventKind.Request, BindingId: 1 })
{
    throw new TimeoutException("No matching request arrived.");
}
RequireOk(service.StartServerSentEvents(request.Exchange));
// Wait for Core to make the response writable before submitting events.
var writeWait = System.Diagnostics.Stopwatch.StartNew();
var writable = service.Take(timeoutMilliseconds: 250);
while (writable is null && writeWait.Elapsed < TimeSpan.FromSeconds(5))
{
    writable = service.Take(timeoutMilliseconds: 250);
}
if (writable is not { Kind: EventKind.ResponseWritable } || !writable.Exchange.Equals(request.Exchange))
{
    throw new InvalidOperationException("The stream did not become writable.");
}
RequireOk(service.WriteServerSentEvent(request.Exchange, new ServerSentEvent(
    Data: "ready", EventType: "state", Id: "1", RetryMilliseconds: 1000)));
RequireOk(service.WriteServerSentEvent(request.Exchange, new ServerSentEvent(Data: "done")));
RequireOk(service.FinishResponseStream(request.Exchange));

service.BeginDrain();
var drain = service.WaitDrained(timeoutMilliseconds: 5000);
service.Stop();
if (drain.State != DrainState.Complete || drain.Status != CoreStatus.Ok)
{
    throw new InvalidOperationException($"Drain ended with {drain.State} ({drain.Status}).");
}
Console.WriteLine("drain complete");

static void RequireOk(CoreStatus status)
{
    if (status != CoreStatus.Ok)
    {
        throw new InvalidOperationException($"Core refused the operation: {status}.");
    }
}
Terminal
dotnet run --project Server.csproj

When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.

Terminal
curl -NsS "$BASE_URL/events"

The client receives data: ready and data: done before the stream ends. The handler waits for a writable event from the same request before submitting output.

SSE flow and reconnect

Advanced

Echo a WebSocket message

Save this file as Program.cs, replacing the previous episode’s source.

Program.cs
using CoAkka.Http;
using System.Text;

HttpListenerOptions listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
var route = new HttpRoute(RouteId: 1, BindingId: 1, Method: "GET", Pattern: "/socket", WebSocket: true);
using var service = new HttpService(listener, routes: [route]);
service.Start();
Console.WriteLine($"http://127.0.0.1:{service.Port}/socket");

var waitStarted = System.Diagnostics.Stopwatch.StartNew();
var request = service.Take(timeoutMilliseconds: 250);
while (request is null && waitStarted.Elapsed < TimeSpan.FromMinutes(1))
{
    request = service.Take(timeoutMilliseconds: 250);
}
if (request is not { Kind: EventKind.Request, BindingId: 1 })
{
    throw new TimeoutException("No matching request arrived.");
}
RequireOk(service.AcceptWebSocket(request.Exchange, subprotocol: "coakka.demo"));
var deadline = System.Diagnostics.Stopwatch.StartNew();
bool closed = false;
while (deadline.Elapsed < TimeSpan.FromSeconds(45))
{
    var frame = service.TakeWebSocket(timeoutMilliseconds: 500);
    switch (frame?.Kind)
    {
        case WebSocketEventKind.Open:
            RequireOk(service.SendWebSocket(frame.Session, WebSocketEventKind.Text, "hello"u8));
            break;
        case WebSocketEventKind.Text:
            RequireOk(service.SendWebSocket(frame.Session, WebSocketEventKind.Text,
                Encoding.UTF8.GetBytes("echo: " + Encoding.UTF8.GetString(frame.Data))));
            break;
        case WebSocketEventKind.Close:
            closed = true;
            break;
        case WebSocketEventKind.AcceptFailed:
            throw new InvalidOperationException("The WebSocket handshake failed.");
    }
    if (closed)
    {
        break;
    }
}
if (!closed)
{
    throw new TimeoutException("The client did not close the WebSocket.");
}

service.BeginDrain();
var drain = service.WaitDrained(timeoutMilliseconds: 5000);
service.Stop();
if (drain.State != DrainState.Complete || drain.Status != CoreStatus.Ok)
{
    throw new InvalidOperationException($"Drain ended with {drain.State} ({drain.Status}).");
}
Console.WriteLine("drain complete");

static void RequireOk(CoreStatus status)
{
    if (status != CoreStatus.Ok)
    {
        throw new InvalidOperationException($"Core refused the operation: {status}.");
    }
}
Terminal
dotnet run --project Server.csproj

Use a browser console on a local HTTP page. Replace 49321 with the printed port.

JavaScript
const socket = new WebSocket("ws://127.0.0.1:49321/socket", "coakka.demo");
socket.onmessage = ({ data }) => {
  console.log(data);
  if (data === "hello") {
    socket.send("ping");
  } else if (data === "echo: ping") {
    socket.close();
  }
};

Expect the greeting and echo: ping. The client closes the session, then the process drains. The example uses one WebSocket session on loopback.

WebSocket lifecycle and failure modes

Advanced

Choose the listener profile

Use a standalone listener for file responses, streams and WebSockets in these lessons. Choose MultiProtocol for buffered HTTP/1.1, HTTP/2 and HTTP/3 on one TLS port.

Run the full C# protocol project · Certificates and reload

Advanced

Observe completion and drain

Save this file as Program.cs, replacing the previous episode’s source.

Program.cs
using CoAkka.Http;

HttpListenerOptions listener = HttpListenerOptions.Standalone(
    HttpProtocol.Http11, bindAddress: "127.0.0.1", port: 0);
var route = new HttpRoute(RouteId: 1, BindingId: 1, Method: "GET", Pattern: "/hello/Ada");
using var service = new HttpService(listener, routes: [route], staticMounts: [], fileAuthorities: [],
    monitor: new MonitorOptions(MonitorCategories.Exchange));
service.Start();
Console.WriteLine($"http://127.0.0.1:{service.Port}/hello/Ada");

var waitStarted = System.Diagnostics.Stopwatch.StartNew();
var request = service.Take(timeoutMilliseconds: 250);
while (request is null && waitStarted.Elapsed < TimeSpan.FromMinutes(1))
{
    request = service.Take(timeoutMilliseconds: 250);
}
if (request is not { Kind: EventKind.Request, BindingId: 1 })
{
    throw new TimeoutException("No matching request arrived.");
}
RequireOk(service.Respond(request.Exchange, status: 200, body: "hello Ada"u8.ToArray()));

service.BeginDrain();
var drain = service.WaitDrained(timeoutMilliseconds: 5000);
var snapshot = service.ReadMonitor();
if (!snapshot.Collecting || snapshot.AdmittedRequests == 0 || snapshot.Completed == 0)
{
    throw new InvalidOperationException("Monitor did not report the completed request.");
}
Console.WriteLine($"admitted={snapshot.AdmittedRequests}, completed={snapshot.Completed}");
service.Stop();
if (drain.State != DrainState.Complete || drain.Status != CoreStatus.Ok)
{
    throw new InvalidOperationException($"Drain ended with {drain.State} ({drain.Status}).");
}
Console.WriteLine("drain complete");

static void RequireOk(CoreStatus status)
{
    if (status != CoreStatus.Ok)
    {
        throw new InvalidOperationException($"Core refused the operation: {status}.");
    }
}
Terminal
dotnet run --project Server.csproj

When the server prints its URL, set BASE_URL in a second terminal to its scheme, address and port. For example, use BASE_URL=http://127.0.0.1:49321 if it prints port 49321.

Terminal
curl -isS "$BASE_URL/hello/Ada"

After 200 hello Ada, look for the admitted and completed counts and drain complete in the service terminal. Drain stops admitting new work and lets accepted work finish within the wait. A timeout requires checking the returned drain state before disposal.

Monitor fields · Live controls · Try a held request