Study · NuGet · 2.3.2
Học CoAkka HTTP Runtime với C#
Bắt đầu với một yêu cầu trong một tiến trình. Sau đó thực hành gửi tệp, phát sự kiện, mở WebSocket và theo dõi dịch vụ xử lý xong.
Beginner
Cài connector
Dùng .NET SDK 8 trở lên và tạo thư mục dự án riêng. Tệp dự án ghim CoAkka.Http.Runtime 2.3.2 qua NuGet.
dotnet --version
<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>
Trong 2.3.2, 2.3 là thế hệ Core và 2 là số thứ tự của bản phát hành connector của connector trên Core đó. Gói kèm thư viện native tương ứng.
Beginner
Chạy yêu cầu đầu tiên
Lưu mã dưới đây thành 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}.");
}
}
dotnet run --project Server.csproj
Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.
curl -isS "$BASE_URL/hello/Ada"
Kết quả đúng là 200 và hello Ada. Server xử lý một yêu cầu khớp route, drain rồi thoát. Giá trị cổng 0 để hệ điều hành chọn cổng trống.
Beginner
Đọc yêu cầu
Chạy lại ví dụ đầu tiên và gọi /hello/Ada?tag=one&tag=two&flag. Kết quả vẫn là hello Ada. Xem request trong debugger để thấy 3 mục query theo đúng thứ tự.
PathParameters- Giá trị
namekhớp với/hello/{name}. Giải mã và xác thực khi nghiệp vụ cần. QueryParameters- Giữ thứ tự, các khóa lặp và phân biệt giá trị vắng mặt với chuỗi rỗng.
Headers- Đọc giá trị handler cần sau khi Core đã khớp phương thức và đường dẫn.
Body- Nội dung yêu cầu đã được đọc vào bộ đệm. Chọn route streaming khi cần xử lý từng phần.
Beginner
Gọi dịch vụ upstream
Dùng Python 3.11 trở lên để mở upstream HTTP/1.1 trong terminal riêng.
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
Lưu mã dưới đây thành Program.cs và thay nội dung của tập trước.
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();
dotnet run --project Server.csproj
Kết quả đúng là HTTP 200 rồi hello upstream. Hạn 3 giây của yêu cầu và thời gian chờ kết quả 5 giây có mục đích riêng. Bấm Ctrl+C để dừng upstream sau khi thử.
Advanced
Gửi tệp cho client
Tạo một tệp thử. File authority giới hạn tệp mà handler được chọn trong thư mục này, đồng thời giới hạn số tệp đang gửi và kích thước.
mkdir -p files
printf '%s\n' 'CoAkka file delivery' > files/manual.txt
Lưu mã dưới đây thành Program.cs và thay nội dung của tập trước.
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}.");
}
}
dotnet run --project Server.csproj
Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.
curl -isS "$BASE_URL/download"
Kết quả là nội dung tệp files/manual.txt. Ví dụ gửi tệp từ server về client. Để gửi tệp theo chiều ngược lại, xem hướng dẫn tải tệp · bài thực hành upload.
Advanced
Gửi 2 sự kiện SSE
Lưu mã dưới đây thành Program.cs và thay nội dung của tập trước.
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}.");
}
}
dotnet run --project Server.csproj
Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.
curl -NsS "$BASE_URL/events"
Client nhận data: ready rồi data: done trước khi luồng kết thúc. Handler chờ sự kiện cho phép ghi của đúng yêu cầu rồi mới gửi dữ liệu.
Advanced
Phản hồi tin nhắn WebSocket
Lưu mã dưới đây thành Program.cs và thay nội dung của tập trước.
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}.");
}
}
dotnet run --project Server.csproj
Dùng console của trình duyệt trên một trang HTTP cục bộ. Thay 49321 bằng cổng mà server in ra.
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();
}
};
Kết quả gồm lời chào và echo: ping. Client đóng phiên rồi tiến trình drain. Ví dụ chạy một phiên WebSocket trên loopback.
Advanced
Chọn cấu hình listener
Các bài gửi tệp, streaming và WebSocket ở đây dùng listener đơn. Chọn MultiProtocol khi muốn phục vụ HTTP/1.1, HTTP/2 và HTTP/3 cùng cổng TLS cho yêu cầu và phản hồi có bộ đệm.
Chạy project C# với 3 giao thức · Chứng chỉ và thay chứng chỉ
Advanced
Theo dõi yêu cầu và drain
Lưu mã dưới đây thành Program.cs và thay nội dung của tập trước.
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}.");
}
}
dotnet run --project Server.csproj
Khi server in URL, đặt BASE_URL trong terminal thứ hai bằng giao thức, địa chỉ và cổng đã in. Ví dụ, dùng BASE_URL=http://127.0.0.1:49321 nếu cổng là 49321.
curl -isS "$BASE_URL/hello/Ada"
Sau 200 hello Ada, xem số yêu cầu đã nhận, đã hoàn tất và dòng drain complete trong terminal của server. Drain ngừng nhận việc mới để xử lý nốt việc đã nhận trong thời hạn chờ. Khi hết hạn, đọc trạng thái drain trước khi giải phóng service.
Các thuộc tính của Monitor · Điều khiển khi đang chạy · Thử giữ một yêu cầu khi drain