Skip to content

cHttpServer Component Overview

Introduction

cHttpServer is an HTTP server component based on VB6 that provides complete Web server functionality, supporting routing, session, cookie, static file service, SSE (Server-Sent Events), CORS handling, and more.

Features

FeatureDescription
HTTP ServiceSupports GET/POST/PUT/DELETE/OPTIONS methods
Router SystemSupports manual route registration, parameter routing {param}, and auto routing
Session ManagementSupports memory, file system, database storage
Cookie HandlingComplete cookie parsing and setting
Static FilesAuto serve static files, built-in default documents and directory redirect
Static File CacheLazy content cache + ETag/304 negotiated cache, auto-sense file updates
SSE SupportServer-Sent Events real-time push
CORS HandlingBuilt-in CORS support
HTTPS/TLSChain-function TLS certificate configuration, supports PFX/PEM/Windows certificate store
MVC ArchitectureSupports controller-view-model development
Packet CoalescingAuto handles TCP packet coalescing
Connection ManagementMax connections limit, idle timeout cleanup, request body size limit

Architecture Overview

┌─────────────────────────────────────────────────────────┐
│                     cHttpServer                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Router    │  │   Session   │  │    SSE      │     │
│  │  (Router)   │  │  (Session)  │  │(Real-time)  │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Request   │  │  Response   │  │   Context   │     │
│  │(Request Obj)│  │ (Response)   │  │  (Context)   │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘

Quick Start

Minimal HTTP Server

vb
Private WithEvents Server As cHttpServer

Private Sub Form_Load()
    Set Server = New cHttpServer

    ' Register controller
    Call Server.Router.Reg("Home", New cHomeController)

    ' Exact routes
    Call Server.Router.Add("/", "Home@Index")
    Call Server.Router.Add("/user", "Home@User", OnlyGet)

    ' Parameter routes
    Call Server.Router.Add("/api/user/{id}", "Home@GetUser", OnlyGet)
    Call Server.Router.Add("/api/user/{userId}/post/{postId}", "Home@GetPost", OnlyGet)

    ' Start server
    If Server.WebRoot("C:\WebRoot").Start(8080) Then
        Debug.Print "Server started: http://localhost:8080"
    Else
        Debug.Print "Start failed: " & Server.LastError
    End If
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Server.StopMe
End Sub

' Controller example
Public Sub Index(ctx As cHttpServerContext)
    ctx.Response.Html "<h1>Hello World!</h1>"
End Sub

Public Sub GetUser(ctx As cHttpServerContext)
    ' Get id via parameter route
    Dim id As String
    id = ctx.Request.RouteParams("id")
    ctx.Response.Json Array("userId" & id)
End Sub

Public Sub GetPost(ctx As cHttpServerContext)
    ' Multi-parameter route
    Dim uid As String, pid As String
    uid = ctx.Request.RouteParams("userId")
    pid = ctx.Request.RouteParams("postId")
    ctx.Response.Json Array(uid, pid)
End Sub

Public Sub Api(ctx As cHttpServerContext)
    Dim data As New Dictionary
    data("message") = "Success"
    data("time") = Now
    ctx.Response.Json data, 0, "OK"
End Sub

Session Configuration

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' Configure Session storage type
    Server.SessionStorageType = SessionStorageFileSystem  ' File storage
    Server.SessionStoragePath = "C:\Sessions"             ' Storage path
    Server.SessionCookieName = "MY_SESSIONID"             ' Cookie name

    ' Or use database storage
    ' Server.SessionStorageType = SessionStorageDatabase
    ' Server.SessionStoragePath = "sessions_table"

    Call Server.WebRoot("C:\WebRoot").Start(8080)
End Sub

Connection Management Configuration

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' Recommended production configuration
    Server.MaxConnections = 500          ' Max concurrent connections (default 1000)
    Server.MaxRequestSize = 5242880      ' Max request body 5MB (default 10MB)
    Server.IdleTimeoutSeconds = 60       ' Idle timeout 60 seconds (default 120)
    Server.CleanupTimerInterval = 15000  ' Auto cleanup every 15 seconds (default 30 seconds)

    Call Server.WebRoot("C:\WebRoot").Start(8080)
End Sub

' Monitor current connection count
Debug.Print "Current connections: " & Server.ConnectionCount

' Note: Built-in timer automatically cleans up idle connections and expired sessions, no external timer needed
Call Server.CleanupIdleConnections

HTTPS Configuration

vb
' Start HTTPS with PEM certificates
Server.TlsCertFile("C:\certs\fullchain.pem|C:\certs\privkey.pem").Start 443

' Start HTTPS with PFX certificate + WebRoot
Server.TlsCertFile("C:\certs\server.pfx", "password").WebRoot("C:\www").Start 443

' HTTP + HTTPS dual port
Dim httpSvr As New cHttpServer
httpSvr.WebRoot("C:\www").Start 80

Dim httpsSvr As New cHttpServer
httpsSvr.TlsCertFile("C:\certs\server.pfx", "pwd").WebRoot("C:\www").Start 443

See TLS/HTTPS Support | Certificate Modes

CORS Configuration

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' Enable CORS
    Server.CrossDomain.Enable = True
    Server.CrossDomain.AllowOrigin = "*"
    Server.CrossDomain.AllowMethods = "GET, POST, PUT, DELETE"
    Server.CrossDomain.AllowHeaders = "Content-Type, Authorization"
    Server.CrossDomain.AllowCredentials = True

    Call Server.Start(8080)
End Sub

File Structure

FileDescription
cHttpServer.clsMain server class
cHttpServerRouter.clsRouter (supports exact matching and parameter routing)
cHttpServerRouteItem.clsRoute item (parameter route pattern parsing and matching)
cHttpServerRequest.clsRequest object
cHttpServerResponse.clsResponse object (with ETag/304/lazy cache)
cHttpServerSession.clsSession management
cHttpServerCookies.clsCookie management
cHttpServerContext.clsContext object
cHttpServerClientInfo.clsClient info
cHttpServerFileCacheEntry.clsStatic file cache entry (content+ETag+time)
cHttpServerRouteBefore.clsBefore route
cHttpServerRouterAfter.clsAfter route
cHttpCrossDomain.clsCORS handling
cClientCallback.clsConnection callback (Socket events, buffer management)

References

  • cTlsReMaster.cls - TLS/Network communication
  • cJson.cls - JSON handling
  • cScriptEngine.cls - Script engine
  • cDataBase.cls - Database (optional)
  • cSSE.cls - SSE support

Connection Management Properties

PropertyTypeDefaultDescription
MaxConnectionsLong1000Max concurrent connections, reject new when exceeded
MaxRequestSizeLong10485760 (10MB)Max request body size in bytes, disconnect when exceeded
IdleTimeoutSecondsLong120Idle connection timeout in seconds, 0 means no checking
ConnectionCountLong (read-only)-Current active connection count
CleanupTimerIntervalLong30000 (30s)Built-in cleanup timer interval (ms), auto cleans idle connections and expired sessions
MaxCacheFileSizeLong1048576 (1MB)Static file single-file cache limit in bytes, 0=disable content cache
CacheTTLSecondsLong300 (5min)Cache TTL in seconds, check ETag after expiry to decide refresh
MethodDescription
AddDefaultDocument(FileName)Add custom default document
RefreshCache()Refresh directory structure cache (call after deploying new files)
ClearFileCache()Clear all file content cache (force release memory)

See Methods Reference | Security Practices


Last Updated: 2026-06-22

VB6 and LOGO copyright of Microsoft Corporation