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 SubSession 配置
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.CleanupIdleConnectionsHTTPS 配置
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.cls | Session 管理 |
cHttpServerCookies.cls | Cookie 管理 |
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 支持
连接管理属性
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
MaxConnections | Long | 1000 | 最大并发连接数,超限拒绝新连接 |
MaxRequestSize | Long | 10485760 (10MB) | 最大请求体字节数,超限断开连接 |
IdleTimeoutSeconds | Long | 120 | 空闲连接超时秒数,0 表示不检测 |
ConnectionCount | Long (只读) | - | 当前活跃连接数 |
CleanupTimerInterval | Long | 30000 (30秒) | 内置清理定时器间隔(毫秒),自动清理空闲连接和过期 Session |
MaxCacheFileSize | Long | 1048576 (1MB) | 静态文件单文件缓存上限字节,0=禁用内容缓存 |
CacheTTLSeconds | Long | 300 (5分钟) | 缓存TTL秒数,过期后检查ETag决定刷新 |
| 方法 | 说明 |
|---|---|
AddDefaultDocument(FileName) | 添加自定义默认文档 |
RefreshCache() | 刷新目录结构缓存(部署新文件后调用) |
ClearFileCache() | 清空所有文件内容缓存(强制释放内存) |
最后更新: 2026-06-22