DEV Community

Cover image for PicoServer Progressive Usage Guide (VB.NET Version)
ben
ben

Posted on

PicoServer Progressive Usage Guide (VB.NET Version)

🧰 PicoServer Progressive Usage Guide

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.

Private ReadOnly MyAPI As New WebAPIServer

Sub Main()
    ' Start the server (default port: 8090)
    MyAPI.StartServer()
    ' Register route (see mapping methods below)
    MyAPI.AddRoute("/", AddressOf hello, "GET")
    Console.ReadKey()
End Sub

Enter fullscreen mode Exit fullscreen mode

Related Methods

' Add routes to the whitelist; whitelisted routes bypass middleware processing
MyAPI.RouteWhiteList.Add("/hello")
MyAPI.ClearRoutes() ' Clear all routes
MyAPI.StopServer() ' Stop the server
Enter fullscreen mode Exit fullscreen mode

2. Three Ways to Map Routes

PicoServer offers flexible route configuration methods:

  1. Method Mapping: The most commonly used method with clear logic and restricted request methods. MyAPI.AddRoute("/hello", AddressOf hello, "GET")
Private Async Function hello(request As HttpListenerRequest, response As HttpListenerResponse) As Task
    Dim name = request.GetQuery("name") ' Get URL query parameters
    If name = "" Then
        name = "PicoServer"
    End If
    Await response.WriteAsync(<t>{"code":1,"msg":"Hello <%= name %> WebAPI"}</t>.Value)
End Function
Enter fullscreen mode Exit fullscreen mode
  1. Anonymous Function: Ideal for logic that can be implemented in a single line of code.
MyAPI.AddRoute("/status", Function(req, resp) resp.WriteAsync("OK"), "GET")
Enter fullscreen mode Exit fullscreen mode
  1. Multi-Action Routing: No method restrictions, with judgment and distribution implemented in the logic. MyAPI.AddRoute("/user", AddressOf userHandle)
Private Async Function users(request As HttpListenerRequest, response As HttpListenerResponse) As Task
    Select Case request.HttpMethod
        Case "GET"
            ' Generate a JWT Token valid for 1 hour
            Dim token = MyAPI.JWT.GenerateToken(<t>{"username":"PicoServer","exp":<%= MyAPI.GetTimeStamp10(60 * 60) %>}</t>.Value)
            ' Return user information request with Token attached
            Await response.WriteAsync(<t>{"code":1,"msg":"Successfully retrieved user information","data":{"username":"PicoServer","age":30},"token":"<%= token %>"}</t>.Value)
        Case "POST"
            ' Directly decode the JWT Token to get the payload here; built-in authentication automatically verifies Token validity.
            ' Invalid Tokens will be intercepted by middleware and won't execute to this point.
            Dim payload = MyAPI.JWT.DecodePayload(request.GetToken)
            ' Further validate Token validity and expiration time if needed

            ' Assume the request body is in JSON format and contains user information
            Await response.WriteAsync(<t>{"code":1,"msg":"User created successfully","data":<%= payload %>}</t>.Value)
        Case Else
            response.StatusCode = 405 ' Method Not Allowed
            Await response.WriteAsync(<t>{"code":0,"msg":"Method not allowed"}</t>.Value)
    End Select
End Function
Enter fullscreen mode Exit fullscreen mode

Built-in Methods

' Get the request body as a string
Dim body = Await request.ReadBodyAsString
' Two built-in timestamp methods
MyAPI.GetTimeStamp13(60 * 60 * 1000) ' Get current 13-digit timestamp plus 1 hour validity (in milliseconds); no parameter for current time only
MyAPI.GetTimeStamp10(60 * 60) ' Get current 10-digit timestamp plus 1 hour validity (in seconds); no parameter for current time only
' Get key-value pairs from POST form data with the following method
Dim name = request.ParseForm()("name")
Enter fullscreen mode Exit fullscreen mode

Chapter 2: Arsenal Extensions (Streaming & Long Connections)

Install these enhancement components when you need to handle large files, real-time monitoring, or intermittent notifications.

Common Methods

' Add a route for file download, restricted to GET method
MyAPI.AddRoute("/download", Function(req, resp) resp.SendFileAsync("E:\3 Life\DadFeeding.mp4"), "GET")
' Add a route for file upload, restricted to POST method; progress callback is an optional parameter
MyAPI.AddRoute("/upload", Function(req, resp) req.SaveFileAsync("E:\3 Life\FileUploadTest\123.data", Sub(cur, total) Console.WriteLine($"Progress: {cur / total}%")), "POST")
Enter fullscreen mode Exit fullscreen mode

1. Video Playback & Preview

asAttachment is True by default (forces download). Set to False for previewing documents, videos and similar files.

' Suitable for video player calls
MyAPI.AddRoute("/mp4", Function(req, resp) resp.SendFileAsync("D:\movie.mp4", False), "GET")

Enter fullscreen mode Exit fullscreen mode

2. Real-Time Live Stream Mode

isLive:=True indicates whether it is a live stream (file or stream). Setting to True enables Chunked transfer encoding with no caching, perfect for security monitoring forwarding.

MyAPI.AddRoute("/live", Function(req, resp)
    Dim fs = New FileStream("camera.mp4", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    Return resp.SendStreamAsync(fs, "video/mp4", isLive:=True)
End Function, "GET")

Enter fullscreen mode Exit fullscreen mode

3. Long Connections & File Uploads

' Long connection push: Be sure to call resp.Close() when finished
MyAPI.AddRoute("/notify", Function(req, resp) resp.WriteChunkAsync("Alarm Message"), "GET")

' File upload: Supports progress callback
MyAPI.AddRoute("/upload", Function(req, resp) req.SaveFileAsync("D:\up.dat", Sub(cur, total) Console.WriteLine($"Progress: {cur * 100 / total}%")), "POST")
Enter fullscreen mode Exit fullscreen mode

Chapter 3: Security Guard (JWT & Middleware)

Intercept or allow requests with middleware before they reach your business logic.

1. Enable Interception and Verification

With just one line of code, automatically validate the Authorization field in the request header.

' Add simple Token verification middleware
MyAPI.AddSimpleTokenVerify("333") ' All routes require Token verification; the parameter is the Token value
' Or use JWT mode
MyAPI.AddJwtTokenVerify("micoroserver779") ' All routes require JWT Token verification; the parameter is the signature secret key

Enter fullscreen mode Exit fullscreen mode

Two built-in identity authentication middlewares provide unified authentication for WebAPI, WebSocket, file uploads and downloads. Routes that do not require authentication can be added to the whitelist with MyAPI.RouteWhiteList.Add("/hello").

2. Identity Token Operations

Built-in timestamp tools let you generate Tokens that can be directly returned as responses.

' Universal method to get Token
Dim token = request.GetToken

' Generate a JWT valid for 1 hour (3600 seconds)
Dim exp = MyAPI.GetTimeStamp10(3600)
Dim jwttoken = MyAPI.JWT.GenerateToken(<t>{"user":"admin","exp":<%= exp %>}</t>.Value)

' Decode Token to get payload in routes
Dim payload = MyAPI.JWT.DecodePayload(request.GetToken)

Enter fullscreen mode Exit fullscreen mode

Chapter 4: Real-Time Communication (WebSocket)

Enable the WebSocket server and client when low-latency, bidirectional data exchange is required.

WebSocket Server

1. Configuration & Enabling

MyAPI.enableWebSocket = True
MyAPI.WsOnConnectionChanged = AddressOf WsConnectChanged
MyAPI.WsOnMessage = AddressOf OnMessageReceived

Enter fullscreen mode Exit fullscreen mode

2. State & Message Handling

Private Async Function OnMessageReceived(clientId As String, msg As String, sendReply As Func(Of String, Task)) As Task
    Console.WriteLine($"Received message from {clientId}: {msg}")
    ' Example: Reply to the client
    Await sendReply($"I have received: {msg}")
End Function

Private Sub WsConnectChanged(clientId As String, connected As Boolean)
    If connected Then
        Console.WriteLine($"WS Client {clientId} connected")
    Else
        Console.WriteLine($"WS Client {clientId} disconnected")
    End If
End Sub

Enter fullscreen mode Exit fullscreen mode

Related Methods

' Get the list of IDs for all currently online WebSocket clients
MyAPI.WsGetOnlineClients()
Enter fullscreen mode Exit fullscreen mode

WebSocket Client

1. Reference & Instance Declaration

Imports PicoServer
Module WebSocketTest
    Private wsClient As WebSocketClient ' WebSocket client instance
    ' Subsequent logic...
End Module
Enter fullscreen mode Exit fullscreen mode

2. Initialization & Event Subscription

' Initialize the client and specify the server address
wsClient = New WebSocketClient("wss://echo.websocket.org/")

' Subscribe to core events
AddHandler wsClient.OnConnected, AddressOf OnConnected ' Connection succeeded
AddHandler wsClient.OnMessageReceived, AddressOf OnMessageReceived ' Message received
AddHandler wsClient.OnDisconnected, AddressOf OnDisconnected ' Connection disconnected
AddHandler wsClient.OnError, AddressOf OnError ' Exception triggered
Enter fullscreen mode Exit fullscreen mode

3. Core Operations

Method Description
wsClient.StartConnect() Start the client and establish a connection to the server
wsClient.SendMessageAsync(message) Asynchronously send a string message to the server
wsClient.StopConnect() Actively disconnect the WebSocket connection

4. Event Callback Examples

' Connection succeeded
Private Sub OnConnected(sender As Object, e As EventArgs)
    Console.WriteLine("Connected successfully!")
End Sub

' Message received
Private Sub OnMessageReceived(sender As Object, message As String)
    Console.WriteLine($"Received message: {message}")
End Sub

' Connection disconnected
Private Sub OnDisconnected(sender As Object, e As EventArgs)
    Console.WriteLine("Connection disconnected!")
End Sub

' Exception handling
Private Sub OnError(sender As Object, e As WebSocketErrorEventArgs)
    Console.WriteLine($"Error: {e.ErrorCode}, {e.ErrorMessage}")
End Sub
Enter fullscreen mode Exit fullscreen mode

Top comments (0)