cHttpServer Methods Reference
🚀 Server Control Methods
Start
Starts HTTP server.
Public Function Start(Optional Port As Long = 80, Optional WebRoot As String = "", Optional IP As String = "0.0.0.0") As BooleanParameters:
Port- Listen port (default 80)WebRoot- Static file root directoryIP- Listen IP address (default 0.0.0.0 means all interfaces)
Returns: Returns True on success, False on failure
Example:
' Basic start
If Server.Start(8080) Then
Debug.Print "Server started successfully"
End If
' With static file directory
If Server.Start(8080, "C:\WebRoot") Then
Debug.Print "Server started successfully"
End If
' Specify IP
If Server.Start(8080, "C:\WebRoot", "127.0.0.1") Then
Debug.Print "Local server started successfully"
End IfStopMe
Stops HTTP server.
Public Function StopMe() As BooleanDescription: Closes all connections, releases resources.
Example:
Private Sub Form_Unload(Cancel As Integer)
Server.StopMe
Set Server = Nothing
End Sub🛣️ Route-Related Methods (via Router Object)
Reg
Registers a controller.
Public Function Reg(ControllerName As String, Controller As Object) As BooleanParameters:
ControllerName- Controller nameController- Controller object instance
Example:
' Register controllers
Call Server.Router.Reg("User", New cUserController)
Call Server.Router.Reg("Api", New cApiController)Add
Adds route rule.
Public Function Add(RouteName As String, Handler As String, Optional MethodLimit As EnumRouteMethod = Any_) As BooleanParameters:
RouteName- Route path (e.g., "/user")Handler- Handler (format: "ControllerName@MethodName")MethodLimit- HTTP method limit:Any_- Any method (default)OnlyGet- GET onlyOnlyPost- POST onlyOnlyPut- PUT onlyOnlyDelete- DELETE only
Example:
' Basic routes
Call Server.Router.Add("/", "Home@Index")
Call Server.Router.Add("/user", "User@List", OnlyGet)
Call Server.Router.Add("/user/create", "User@Create", OnlyPost)
Call Server.Router.Add("/user/update", "User@Update", OnlyPut)
Call Server.Router.Add("/user/delete", "User@Delete", OnlyDelete)📡 Events
OnAccept
Triggers when new connection is accepted.
Public Event OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)Parameters:
ClientInfo- Client info objectDisconnect- Set to True to reject connection
Example:
Private Sub Server_OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)
Debug.Print "New connection: " & ClientInfo.IP & ":" & ClientInfo.Port
' IP blacklist check
If ClientInfo.IP = "192.168.1.100" Then
Disconnect = True ' Reject connection
End If
End SubOnLogs
Log event.
Public Event OnLogs(ByVal Level As String, ByVal Content As String)Example:
Private Sub Server_OnLogs(ByVal Level As String, ByVal Content As String)
Debug.Print "[" & Level & "] " & Content
End Sub🔒 Connection Management
MaxConnections
Maximum concurrent connections.
Public MaxConnections As LongDefault: 1000
Description: When the number of connections reaches this limit, new connections will be rejected (Disconnect = True). Adjust according to server memory and business requirements.
Example:
Server.MaxConnections = 500 ' Set before startingMaxRequestSize
Maximum request body size in bytes.
Public MaxRequestSize As LongDefault: 10485760 (10MB)
Description: When the request body exceeds this size, the connection will be closed and a 413 status code returned. Set to 0 for no limit (not recommended).
Example:
Server.MaxRequestSize = 5242880 ' 5MBIdleTimeoutSeconds
Idle connection timeout in seconds.
Public IdleTimeoutSeconds As LongDefault: 120
Description: If the client does not send data within this time, the server will actively close the connection and release resources. Set to 0 to disable idle checking (not recommended for production). The built-in timer automatically cleans up idle connections every 30 seconds by default, no external timer needed. You can also manually call CleanupIdleConnections().
Example:
Server.IdleTimeoutSeconds = 60 ' 1 minuteConnectionCount
Current active connection count (read-only).
Public Property Get ConnectionCount() As LongExample:
Debug.Print "Current connections: " & Server.ConnectionCountCleanupIdleConnections
Manually clean up idle connections.
Public Sub CleanupIdleConnections()Description: Iterates through the connection pool, closes connections inactive beyond IdleTimeoutSeconds, breaks circular references, and releases resources.
The server's built-in timer automatically calls this method periodically after startup, manual invocation is typically unnecessary.
Example:
' Manual cleanup (usually not needed, built-in timer handles it)
Call Server.CleanupIdleConnections
Debug.Print "Connections: " & Server.ConnectionCountCleanupExpiredSessions
Manually clean up expired sessions.
Public Sub CleanupExpiredSessions()Description: Cleans up expired sessions based on storage type:
- Memory mode: Iterate session dictionary, delete expired items and release resources
- File mode: Scan session directory, delete expired JSON files
- Database mode: Execute DELETE statement to remove expired records
The server's built-in timer automatically calls this method periodically after startup, manual invocation is typically unnecessary.
Example:
' Manual cleanup (usually not needed, built-in timer handles it)
Call Server.CleanupExpiredSessionsCleanupTimerInterval
Built-in cleanup timer interval (milliseconds).
Public Property Get CleanupTimerInterval() As Long
Public Property Let CleanupTimerInterval(ByVal value As Long)Default: 30000 (30 seconds)
Description: After the server starts, a timer is automatically created that executes CleanupIdleConnections and CleanupExpiredSessions at this interval. Set to 0 to disable the built-in timer (not recommended). Changing the interval while the server is running will automatically restart the timer.
Example:
Server.CleanupTimerInterval = 15000 ' Clean up every 15 seconds
' Can also be modified while server is running, takes effect immediately
Server.CleanupTimerInterval = 60000 ' Change to 60 seconds📄 Default Document Configuration
AddDefaultDocument
Add custom default document.
Public Sub AddDefaultDocument(FileName As String)Parameters:
FileName- Default document filename (e.g., "home.html")
Description: Call before Start. Built-in default document list is index.html → index.htm → default.html → default.htm, custom documents are appended to the end. Duplicate additions are automatically ignored.
Example:
Server.AddDefaultDocument "home.html"
Server.AddDefaultDocument "start.html"
Server.WebRoot("C:\WebRoot").Start 8080
' Lookup order: index.html → index.htm → default.html → default.htm → home.html → start.html💾 Static File Cache
MaxCacheFileSize
Single file cache limit (bytes).
Public Property Get MaxCacheFileSize() As Long
Public Property Let MaxCacheFileSize(ByVal value As Long)Default: 1048576 (1MB)
Description: The single file size limit for static file content cache. On first access, if file size ≤ this limit, it's automatically added to memory cache (lazy cache mechanism). Files exceeding this limit are always read from disk, but still enjoy ETag/304 negotiated cache. Set to 0 to disable content cache. Can be modified before Start or at runtime.
Example:
Server.MaxCacheFileSize = 2097152 ' 2MB
Server.MaxCacheFileSize = 0 ' Disable content cache (keep ETag/304 only)CacheTTLSeconds
Cache TTL (seconds).
Public Property Get CacheTTLSeconds() As Long
Public Property Let CacheTTLSeconds(ByVal value As Long)Default: 300 (5 minutes)
Description: The lifetime of cache entries. After expiry, entries are not immediately deleted; instead, on next access, the ETag is checked to determine whether to refresh or renew. Set to 0 for never expire (file updates sensed only via ETag). Can be modified before Start or at runtime.
Example:
Server.CacheTTLSeconds = 600 ' 10 minutes
Server.CacheTTLSeconds = 0 ' Never expireRefreshCache
Refresh directory structure cache.
Public Sub RefreshCache()Description: Manually call after deploying new files/directories to WebRoot to refresh the server's directory structure cache (rootFiles/rootDirs). Does not affect file content cache, which senses file updates via ETag automatically.
Example:
' Refresh after deploying new files
Server.RefreshCacheClearFileCache
Clear all file content cache.
Public Sub ClearFileCache()Description: Force clear all in-memory file content cache, next access will re-read from disk. Suitable for scenarios requiring forced memory release. In most cases, only RefreshCache is needed, content cache senses file updates via ETag automatically.
Example:
' Force clear content cache
Server.ClearFileCache📊 Performance Statistics (Statistics)
Statistics Object
cHttpServerStatistics is the server-level performance statistics container, accessible via Server.Statistics or ctx.Statistics. All fields are Public Long, with zero-overhead increment operations.
Public Statistics As cHttpServerStatisticsRequest Statistics Fields:
| Field | Type | Description |
|---|---|---|
TotalRequests | Long | Cumulative total requests |
GetRequests | Long | GET request count |
PostRequests | Long | POST request count |
PutRequests | Long | PUT request count |
DeleteRequests | Long | DELETE request count |
OptionsRequests | Long | OPTIONS request count |
HeadRequests | Long | HEAD request count |
PatchRequests | Long | PATCH request count |
OtherRequests | Long | Other method request count |
Status Code Statistics Fields:
| Field | Type | Description |
|---|---|---|
Status1xx | Long | 1xx response count |
Status2xx | Long | 2xx response count |
Status3xx | Long | 3xx response count |
Status4xx | Long | 4xx response count |
Status5xx | Long | 5xx response count |
Connection Statistics Fields:
| Field | Type | Description |
|---|---|---|
TotalConnectionsAccepted | Long | Cumulative total connections accepted |
RejectedConnections | Long | Connections rejected due to MaxConnections |
PeakConnections | Long | Peak concurrent connections |
IdleConnectionsCleaned | Long | Connections cleaned due to idle timeout |
Error Statistics Fields:
| Field | Type | Description |
|---|---|---|
RequestErrors | Long | Request processing exceptions |
RequestSizeRejected | Long | 413 Payload Too Large count |
SSEEntryErrors | Long | SSE Entry failure count |
Traffic Statistics Fields:
| Field | Type | Description |
|---|---|---|
TotalBytesReceived | Long | Cumulative bytes received |
TotalBytesSent | Long | Cumulative bytes sent |
SSE/Session/Time Statistics Fields:
| Field | Type | Description |
|---|---|---|
SSEConnectionsAccepted | Long | Total SSE connections |
TotalSessionsCreated | Long | Cumulative total sessions created |
StartTime | Date | Server start time |
Computed Properties:
| Property | Type | Description |
|---|---|---|
UptimeSeconds | Long (Property Get) | Server uptime in seconds |
AverageQPS | Double (Property Get) | Average requests per second |
Methods:
| Method | Description |
|---|---|
Reset() | Reset all statistics counters, StartTime reset to Now |
Example:
' Read statistics in controller
Public Sub GetStats(ctx As cHttpServerContext)
Dim stats As cHttpServerStatistics
Set stats = ctx.Statistics
Dim result As New Dictionary
result("total_requests") = stats.TotalRequests
result("get_requests") = stats.GetRequests
result("post_requests") = stats.PostRequests
result("status_2xx") = stats.Status2xx
result("status_4xx") = stats.Status4xx
result("status_5xx") = stats.Status5xx
result("peak_connections") = stats.PeakConnections
result("uptime_seconds") = stats.UptimeSeconds
result("average_qps") = stats.AverageQPS
ctx.Response.Json result, 0, "Success"
End Sub
' Also accessible via Server directly
Debug.Print "Total: " & Server.Statistics.TotalRequests
Debug.Print "QPS: " & Server.Statistics.AverageQPS
' Reset statistics
Server.Statistics.Reset🔧 Controller Method Writing Specification
Controller methods receive one context parameter containing request and response objects:
Public Sub ActionName(ctx As cHttpServerContext)
' ctx.Request - Request object
' ctx.Response - Response object
' ctx.Session - Session object
' ctx.Cookies - Cookies object
' ctx.Db - Database object (if configured)
End SubExample Controller:
' cUserController.cls
Option Explicit
' GET /user
Public Sub List(ctx As cHttpServerContext)
Dim users As New Dictionary
users("items") = Array("John", "Jane", "Bob")
users("total") = 3
ctx.Response.Json users, 0, "Success"
End Sub
' POST /user/create
Public Sub Create(ctx As cHttpServerContext)
' Get POST data
Dim username As String
username = ctx.Request.Form("username")
' Get JSON data
' username = ctx.Request.Json.GetItem("username")
ctx.Response.Json Nothing, 0, "Created successfully"
End Sub
' GET /user?id=1
Public Sub Detail(ctx As cHttpServerContext)
Dim id As String
id = ctx.Request.QueryString("id")
Dim user As New Dictionary
user("id") = id
user("name") = "John"
ctx.Response.Json user
End Sub📦 Context Object Properties
cHttpServerContext
| Property | Type | Description |
|---|---|---|
Request | cHttpServerRequest | Request object |
Response | cHttpServerResponse | Response object |
Session | cHttpServerSession | Session object |
Cookies | cHttpServerCookies | Cookies object |
Db | cDataBase | Database object |
Server | cHttpServerSvr | Server config |
ClientInfo | cHttpServerClientInfo | Client info |
Statistics | cHttpServerStatistics | Performance statistics object (server-level singleton reference) |
Last Updated: 2026-06-22