VBMAN Middleware and Client Communication Example
Overview
This example demonstrates how to build a web server with middleware using the VBMAN framework, and how to implement client-server communication. The example includes advanced features such as authentication middleware.
Project Structure
MiddleWare/
├── server/ # Server-side project
│ ├── Form1.frm # Server main form
│ ├── DataServer.vbp # Server project file
│ └── include/ # Server-side class libraries
│ ├── bWcs.cls # Business processing class
│ ├── mAuth.cls # Authentication middleware
│ ├── Config.bas # Configuration module
│ └── ToolsHttp.bas # HTTP utility module
└── client/ # Client project
├── Client.frm # Client main form
├── DataClient.vbp # Client project file
└── include/ # Client-side class libraries
├── cHttpClient.cls # HTTP client class
├── bTaskSend.cls # Task sending class
├── bTaskLog.cls # Task logging class
└── cJson.cls # JSON processing class
Core Code Analysis
1. Server-side Middleware Configuration (Form1.frm)
vb
'Server initialization
Dim HttpServer As New VBMANLIB.cHttpServer
Private Sub Form_Load()
With HttpServer
'Register business class
.Router.Reg "Wcs", New bWcs
'Configure pre-middleware for authentication check
.Router.Before.Add "/*", New mAuth
'Start server
.Start 800
End With
End Sub
2. Authentication Middleware (mAuth.cls)
vb
Public Sub Execute(ctx As cHttpServerContext)
'Get authentication information
Dim token As String: token = ctx.Request.Headers("Authorization")
'Terminate request on authentication failure
If Not IsValidToken(token) Then
ctx.Response.State401 "Unauthorized"
ctx.Abort
End If
End Sub
3. Client Request Sending (Client.frm)
vb
Private Sub SendTask()
With New cHttpClient
'Set request headers
.RequestHeaders.Add "Authorization", "Bearer " & token
.RequestHeaders.Add "Content-Type", "application/json"
'Send request
Dim response As String
response = .Fetch(ReqPost, "http://localhost:800/wcs/task", jsonData)
'Handle response
Debug.Print .ReturnJson().Encode(, 2)
End With
End Sub
Feature Description
Middleware System
- Support for pre-middleware (Before)
- Support for post-middleware (After)
- Support for middleware chain calls
- Support for request interception and termination
Authentication
- Token authentication mechanism
- Request header validation
- Configurable validation rules
- Unified error handling
Client Functionality
- HTTP request encapsulation
- Header management
- JSON data processing
- Response handling
Technical Points
- Implementation of middleware mechanism
- Encapsulation of HTTP communication
- Unified handling of authentication
- Client-server interaction
Use Cases
- Web APIs requiring authentication
- Distributed system communication
- Microservice architecture
- Business system integration
Extension Suggestions
- Add more types of middleware
- Implement request rate limiting
- Add data validation middleware
- Implement caching middleware
- Add logging middleware