🧰 PicoServer Progressive Usage Guide (C# Version)
Chapter 1: Basic WebAPI (Out-of-the-Box)
If you only need your application to respond to web requests and return data, this section is all you need.
1. Server Startup & Getting Started
Simply initialize WebAPIServer and call StartServer.
using PicoServer;
// Initialize the server instance
var MyAPI = new WebAPIServer();
void Main()
{
// Start the server (default port: 8090)
MyAPI.StartServer();
// Register route (see mapping methods below)
MyAPI.AddRoute("/", hello, "GET");
Console.ReadKey();
}
Related Management Methods
// Add routes to the whitelist; whitelisted routes bypass middleware processing
MyAPI.RouteWhiteList.Add("/hello");
MyAPI.ClearRoutes(); // Clear all registered routes
MyAPI.StopServer(); // Stop the server
2. Three Ways to Map Routes
-
Method Mapping: Clear logic and easy to maintain.
MyAPI.AddRoute("/hello", hello, "GET");
private async Task hello(HttpListenerRequest request, HttpListenerResponse response)
{
// Get URL query parameters
string name = request.GetQuery("name") ?? "PicoServer";
// Use C# raw string literals for perfect JSON structure presentation
await response.WriteAsync($$"""{"code":1, "msg":"Hello {{name}} WebAPI"}""");
}
- Anonymous Function/Lambda: Ideal for minimal logic.
MyAPI.AddRoute("/status", (req, resp) => resp.WriteAsync("OK"), "GET");
-
Multi-Action Routing: Judge and dispatch within the logic.
MyAPI.AddRoute("/user", users);
private async Task users(HttpListenerRequest request, HttpListenerResponse response)
{
switch (request.HttpMethod)
{
case "GET":
// Generate a JWT Token valid for 1 hour
long exp = MyAPI.GetTimeStamp10(60 * 60);
string token = MyAPI.JWT.GenerateToken($$"""
{
"username": "PicoServer",
"exp": {{exp}}
}
""");
await response.WriteAsync($$"""
{
"code": 1,
"msg": "Successfully retrieved user information",
"data": {"username": "PicoServer", "age": 30},
"token": "{{token}}"
}
""");
break;
case "POST":
// Parse Token payload (invalid Tokens are intercepted by middleware)
string payload = MyAPI.JWT.DecodePayload(request.GetToken());
await response.WriteAsync($$"""{"code":1, "msg":"User created successfully", "data":{{payload}}}""");
break;
default:
response.StatusCode = 405;
await response.WriteAsync("""{"code":0, "msg":"Method not allowed"}""");
break;
}
}
Built-in Methods
string body = await request.ReadBodyAsString(); // Get request body as string
long ts13 = MyAPI.GetTimeStamp13(3600000); // 13-digit timestamp (current time + 1 hour)
long ts10 = MyAPI.GetTimeStamp10(3600); // 10-digit timestamp (current time + 1 hour)
string postName = request.ParseForm()["name"]; // Get POST form key-value pair
Chapter 2: Arsenal Extensions (Streaming & Long Connections)
1. Video Playback & Preview
asAttachment is true by default (force download). Set it to false for video player preview.
// Suitable for video player calls
MyAPI.AddRoute("/mp4", (req, resp) => resp.SendFileAsync(@"D:\movie.mp4", false), "GET");
2. Real-Time Live Stream Mode
isLive: true enables Chunked Transfer Encoding with no caching, perfect for security monitoring forwarding.
MyAPI.AddRoute("/live", (req, resp) => {
var fs = new FileStream("camera.mp4", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return resp.SendStreamAsync(fs, "video/mp4", isLive: true);
}, "GET");
3. Long Connections & File Uploads
// Long connection push: Be sure to call resp.Close() when finished
MyAPI.AddRoute("/notify", (req, resp) => resp.WriteChunkAsync("Alarm message"), "GET");
// File upload: Supports progress callback
MyAPI.AddRoute("/upload", (req, resp) => req.SaveFileAsync(@"D:\up.dat", (cur, total) => Console.WriteLine($"Progress: {cur * 100 / total}%")), "POST");
Chapter 3: Security Guard (JWT & Middleware)
1. Enable Interception and Verification
With just one line of code, automatically validate the Authorization field in the request header.
MyAPI.AddSimpleTokenVerify("333"); // Simple Token mode
MyAPI.AddJwtTokenVerify("micoroserver779"); // JWT mode
Two built-in identity authentication middlewares provide unified authentication for WebAPI, WebSocket, file uploads and downloads, etc. Routes that do not require authentication can be added to the whitelist with MyAPI.RouteWhiteList.Add("/hello");.
2. Identity Token Operations
string token = request.GetToken(); // Universal Token retrieval method
// Generate a JWT valid for 1 hour
string jwt = MyAPI.JWT.GenerateToken($$"""{"user":"admin","exp":{{MyAPI.GetTimeStamp10(3600)}}}""");
// Decode Token payload
string payload = MyAPI.JWT.DecodePayload(token);
Chapter 4: Real-Time Communication (WebSocket)
WebSocket Server
1. Configuration & Enabling
MyAPI.enableWebSocket = true;
MyAPI.WsOnConnectionChanged = WsConnectChanged;
MyAPI.WsOnMessage = OnMessageReceived;
2. State & Message Handling
private async Task OnMessageReceived(string clientId, string msg, Func<string, Task> sendReply)
{
Console.WriteLine($"Message from {clientId}: {msg}");
await sendReply($"Received: {msg}");
}
private void WsConnectChanged(string clientId, bool connected)
{
Console.WriteLine($"Client {clientId} has " + (connected ? "connected" : "disconnected"));
}
// Get list of online client IDs
var onlineClients = MyAPI.WsGetOnlineClients();
WebSocket Client
1. Reference & Instance Declaration
using PicoServer;
class WebSocketTest
{
private WebSocketClient wsClient; // WebSocket client instance
// Subsequent logic...
}
2. Initialization & Event Subscription
// Initialize the client and specify the server address
wsClient = new WebSocketClient("wss://echo.websocket.org/");
// Subscribe to core events
wsClient.OnConnected += OnConnected; // Connection succeeded
wsClient.OnMessageReceived += OnMessageReceived; // Message received
wsClient.OnDisconnected += OnDisconnected; // Connection disconnected
wsClient.OnError += OnError; // Exception triggered
3. Core Operations
| Method | Description |
|---|---|
wsClient.StartConnect() |
Start the client and establish a connection to the server |
wsClient.SendMessageAsync(string message) |
Asynchronously send a string message to the server |
wsClient.StopConnect() |
Actively disconnect the WebSocket connection |
4. Event Callback Examples
// Connection succeeded
private void OnConnected(object sender, EventArgs e)
{
Console.WriteLine("Connected successfully!");
}
// Message received
private void OnMessageReceived(object sender, string message)
{
Console.WriteLine($"Message received: {message}");
}
// Connection disconnected
private void OnDisconnected(object sender, EventArgs e)
{
Console.WriteLine("Connection disconnected!");
}
// Exception handling
private void OnError(object sender, WebSocketErrorEventArgs e)
{
Console.WriteLine($"Error: {e.ErrorCode}, {e.ErrorMessage}");
}
Top comments (0)