Skip to content

cHttpServer 组件概述

简介

cHttpServer 是一个基于 VB6 的 HTTP 服务器组件,提供完整的 Web 服务器功能,支持路由、Session、Cookie、静态文件服务、SSE (Server-Sent Events)、跨域处理等特性。

特性

特性说明
HTTP 服务支持 GET/POST/PUT/DELETE/OPTIONS 方法
路由系统支持手动路由注册、参数路由 {param} 和自动路由
Session 管理支持内存、文件系统、数据库三种存储方式
Cookie 处理完整的 Cookie 解析和设置
静态文件自动提供静态文件服务,内置默认文档、目录重定向
静态文件缓存懒内容缓存 + ETag/304 协商缓存,自动感知文件更新
SSE 支持Server-Sent Events 实时推送
跨域处理内置 CORS 跨域支持
HTTPS/TLS链式函数配置 TLS 证书,支持 PFX/PEM/Windows证书存储
MVC 架构支持控制器-视图-模式开发
粘包处理自动处理 TCP 粘包问题
连接管理最大连接数限制、空闲超时清理、请求体大小限制

架构概览

┌─────────────────────────────────────────────────────────┐
│                     cHttpServer                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Router    │  │   Session   │  │    SSE      │     │
│  │  (路由系统)  │  │  (会话管理)  │  │(实时推送)   │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │   Request   │  │  Response   │  │   Context   │     │
│  │  (请求对象)  │  │  (响应对象)  │  │  (上下文)    │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘

快速开始

最小 HTTP 服务器

vb
Private WithEvents Server As cHttpServer

Private Sub Form_Load()
    Set Server = New cHttpServer

    ' 注册控制器
    Call Server.Router.Reg("Home", New cHomeController)

    ' 精确路由
    Call Server.Router.Add("/", "Home@Index")
    Call Server.Router.Add("/user", "Home@User", OnlyGet)

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

    ' 启动服务器
    If Server.WebRoot("C:\WebRoot").Start(8080) Then
        Debug.Print "服务器启动成功: http://localhost:8080"
    Else
        Debug.Print "启动失败: " & Server.LastError
    End If
End Sub

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

' 控制器示例
Public Sub Index(ctx As cHttpServerContext)
    ctx.Response.Html "<h1>Hello World!</h1>"
End Sub

Public Sub GetUser(ctx As cHttpServerContext)
    ' 通过参数路由获取 id
    Dim id As String
    id = ctx.Request.RouteParams("id")
    ctx.Response.Json Array("userId" & id)
End Sub

Public Sub GetPost(ctx As cHttpServerContext)
    ' 多参数路由
    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 配置

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' 配置 Session 存储方式
    Server.SessionStorageType = SessionStorageFileSystem  ' 文件存储
    Server.SessionStoragePath = "C:\Sessions"             ' 存储路径
    Server.SessionCookieName = "MY_SESSIONID"             ' Cookie 名称

    ' 或使用数据库存储
    ' Server.SessionStorageType = SessionStorageDatabase
    ' Server.SessionStoragePath = "sessions_table"

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

连接管理配置

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' 生产环境建议配置
    Server.MaxConnections = 500          ' 最大并发连接数(默认 1000)
    Server.MaxRequestSize = 5242880      ' 最大请求体 5MB(默认 10MB)
    Server.IdleTimeoutSeconds = 60       ' 空闲超时 60 秒(默认 120)
    Server.CleanupTimerInterval = 15000  ' 每 15 秒自动清理(默认 30 秒)

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

' 监控当前连接数
Debug.Print "当前连接数: " & Server.ConnectionCount

' 注:内置定时器会自动清理空闲连接和过期 Session,无需外部定时器
Call Server.CleanupIdleConnections

HTTPS 配置

vb
' 使用 PEM 证书启动 HTTPS
Server.TlsCertFile("C:\certs\fullchain.pem|C:\certs\privkey.pem").Start 443

' 使用 PFX 证书 + WebRoot
Server.TlsCertFile("C:\certs\server.pfx", "password").WebRoot("C:\www").Start 443

' HTTP + HTTPS 双端口
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

详见 TLS/HTTPS 支持 | 证书模式详解

跨域配置

vb
Private Sub Form_Load()
    Set Server = New cHttpServer

    ' 启用跨域
    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

文件结构

文件说明
cHttpServer.cls主服务器类
cHttpServerRouter.cls路由器(支持精确匹配和参数路由)
cHttpServerRouteItem.cls路由项(参数路由模式解析与匹配)
cHttpServerRequest.cls请求对象
cHttpServerResponse.cls响应对象(含 ETag/304/懒缓存)
cHttpServerSession.clsSession 管理
cHttpServerCookies.clsCookie 管理
cHttpServerContext.cls上下文对象
cHttpServerClientInfo.cls客户端信息
cHttpServerFileCacheEntry.cls静态文件缓存条目(内容+ETag+时间)
cHttpServerRouteBefore.cls前置路由
cHttpServerRouterAfter.cls后置路由
cHttpCrossDomain.cls跨域处理
cClientCallback.cls连接回调(Socket 事件、缓冲区管理)

引用组件

  • cTlsReMaster.cls - TLS/网络通信
  • cJson.cls - JSON 处理
  • cScriptEngine.cls - 脚本引擎
  • cDataBase.cls - 数据库(可选)
  • cSSE.cls - SSE 支持

连接管理属性

属性类型默认值说明
MaxConnectionsLong1000最大并发连接数,超限拒绝新连接
MaxRequestSizeLong10485760 (10MB)最大请求体字节数,超限断开连接
IdleTimeoutSecondsLong120空闲连接超时秒数,0 表示不检测
ConnectionCountLong (只读)-当前活跃连接数
CleanupTimerIntervalLong30000 (30秒)内置清理定时器间隔(毫秒),自动清理空闲连接和过期 Session
MaxCacheFileSizeLong1048576 (1MB)静态文件单文件缓存上限字节,0=禁用内容缓存
CacheTTLSecondsLong300 (5分钟)缓存TTL秒数,过期后检查ETag决定刷新
方法说明
AddDefaultDocument(FileName)添加自定义默认文档
RefreshCache()刷新目录结构缓存(部署新文件后调用)
ClearFileCache()清空所有文件内容缓存(强制释放内存)

详细说明参见 方法参考 | 安全实践


最后更新: 2026-06-22

VB6及其LOGO版权为微软公司所有