Skip to content

cHttpServer Methods Reference

🚀 Server Control Methods

Start

Starts HTTP server.

vb
Public Function Start(Optional Port As Long = 80, Optional WebRoot As String = "", Optional IP As String = "0.0.0.0") As Boolean

Parameters:

  • Port - Listen port (default 80)
  • WebRoot - Static file root directory
  • IP - Listen IP address (default 0.0.0.0 means all interfaces)

Returns: Returns True on success, False on failure

Example:

vb
' 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 If

StopMe

Stops HTTP server.

vb
Public Function StopMe() As Boolean

Description: Closes all connections, releases resources.

Example:

vb
Private Sub Form_Unload(Cancel As Integer)
    Server.StopMe
    Set Server = Nothing
End Sub

Reg

Registers a controller.

vb
Public Function Reg(ControllerName As String, Controller As Object) As Boolean

Parameters:

  • ControllerName - Controller name
  • Controller - Controller object instance

Example:

vb
' Register controllers
Call Server.Router.Reg("User", New cUserController)
Call Server.Router.Reg("Api", New cApiController)

Add

Adds route rule.

vb
Public Function Add(RouteName As String, Handler As String, Optional MethodLimit As EnumRouteMethod = Any_) As Boolean

Parameters:

  • RouteName - Route path (e.g., "/user")
  • Handler - Handler (format: "ControllerName@MethodName")
  • MethodLimit - HTTP method limit:
    • Any_ - Any method (default)
    • OnlyGet - GET only
    • OnlyPost - POST only
    • OnlyPut - PUT only
    • OnlyDelete - DELETE only

Example:

vb
' 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.

vb
Public Event OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)

Parameters:

  • ClientInfo - Client info object
  • Disconnect - Set to True to reject connection

Example:

vb
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 Sub

OnLogs

Log event.

vb
Public Event OnLogs(ByVal Level As String, ByVal Content As String)

Example:

vb
Private Sub Server_OnLogs(ByVal Level As String, ByVal Content As String)
    Debug.Print "[" & Level & "] " & Content
End Sub

🔒 Connection Management

MaxConnections

Maximum concurrent connections.

vb
Public MaxConnections As Long

Default: 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:

vb
Server.MaxConnections = 500  ' Set before starting

MaxRequestSize

Maximum request body size in bytes.

vb
Public MaxRequestSize As Long

Default: 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:

vb
Server.MaxRequestSize = 5242880  ' 5MB

IdleTimeoutSeconds

Idle connection timeout in seconds.

vb
Public IdleTimeoutSeconds As Long

Default: 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:

vb
Server.IdleTimeoutSeconds = 60  ' 1 minute

ConnectionCount

Current active connection count (read-only).

vb
Public Property Get ConnectionCount() As Long

Example:

vb
Debug.Print "Current connections: " & Server.ConnectionCount

CleanupIdleConnections

Manually clean up idle connections.

vb
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:

vb
' Manual cleanup (usually not needed, built-in timer handles it)
Call Server.CleanupIdleConnections
Debug.Print "Connections: " & Server.ConnectionCount

CleanupExpiredSessions

Manually clean up expired sessions.

vb
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:

vb
' Manual cleanup (usually not needed, built-in timer handles it)
Call Server.CleanupExpiredSessions

CleanupTimerInterval

Built-in cleanup timer interval (milliseconds).

vb
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:

vb
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.

vb
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:

vb
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).

vb
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:

vb
Server.MaxCacheFileSize = 2097152  ' 2MB
Server.MaxCacheFileSize = 0         ' Disable content cache (keep ETag/304 only)

CacheTTLSeconds

Cache TTL (seconds).

vb
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:

vb
Server.CacheTTLSeconds = 600   ' 10 minutes
Server.CacheTTLSeconds = 0     ' Never expire

RefreshCache

Refresh directory structure cache.

vb
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:

vb
' Refresh after deploying new files
Server.RefreshCache

ClearFileCache

Clear all file content cache.

vb
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:

vb
' 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.

vb
Public Statistics As cHttpServerStatistics

Request Statistics Fields:

FieldTypeDescription
TotalRequestsLongCumulative total requests
GetRequestsLongGET request count
PostRequestsLongPOST request count
PutRequestsLongPUT request count
DeleteRequestsLongDELETE request count
OptionsRequestsLongOPTIONS request count
HeadRequestsLongHEAD request count
PatchRequestsLongPATCH request count
OtherRequestsLongOther method request count

Status Code Statistics Fields:

FieldTypeDescription
Status1xxLong1xx response count
Status2xxLong2xx response count
Status3xxLong3xx response count
Status4xxLong4xx response count
Status5xxLong5xx response count

Connection Statistics Fields:

FieldTypeDescription
TotalConnectionsAcceptedLongCumulative total connections accepted
RejectedConnectionsLongConnections rejected due to MaxConnections
PeakConnectionsLongPeak concurrent connections
IdleConnectionsCleanedLongConnections cleaned due to idle timeout

Error Statistics Fields:

FieldTypeDescription
RequestErrorsLongRequest processing exceptions
RequestSizeRejectedLong413 Payload Too Large count
SSEEntryErrorsLongSSE Entry failure count

Traffic Statistics Fields:

FieldTypeDescription
TotalBytesReceivedLongCumulative bytes received
TotalBytesSentLongCumulative bytes sent

SSE/Session/Time Statistics Fields:

FieldTypeDescription
SSEConnectionsAcceptedLongTotal SSE connections
TotalSessionsCreatedLongCumulative total sessions created
StartTimeDateServer start time

Computed Properties:

PropertyTypeDescription
UptimeSecondsLong (Property Get)Server uptime in seconds
AverageQPSDouble (Property Get)Average requests per second

Methods:

MethodDescription
Reset()Reset all statistics counters, StartTime reset to Now

Example:

vb
' 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:

vb
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 Sub

Example Controller:

vb
' 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

PropertyTypeDescription
RequestcHttpServerRequestRequest object
ResponsecHttpServerResponseResponse object
SessioncHttpServerSessionSession object
CookiescHttpServerCookiesCookies object
DbcDataBaseDatabase object
ServercHttpServerSvrServer config
ClientInfocHttpServerClientInfoClient info
StatisticscHttpServerStatisticsPerformance statistics object (server-level singleton reference)

Last Updated: 2026-06-22

VB6 and LOGO copyright of Microsoft Corporation