cHttpServer 方法参考
🚀 服务器控制方法
Start
启动 HTTP 服务器。
Public Function Start(Optional Port As Long = 80, Optional WebRoot As String = "", Optional IP As String = "0.0.0.0") As Boolean参数:
Port- 监听端口(默认 80)WebRoot- 静态文件根目录IP- 监听 IP 地址(默认 0.0.0.0 表示所有接口)
返回: 成功返回 True,失败返回 False
示例:
' 基本启动
If Server.Start(8080) Then
Debug.Print "服务器启动成功"
End If
' 带静态文件目录
If Server.Start(8080, "C:\WebRoot") Then
Debug.Print "服务器启动成功"
End If
' 指定 IP
If Server.Start(8080, "C:\WebRoot", "127.0.0.1") Then
Debug.Print "本地服务器启动成功"
End IfStopMe
停止 HTTP 服务器。
Public Function StopMe() As Boolean说明: 关闭所有连接,释放资源。
示例:
Private Sub Form_Unload(Cancel As Integer)
Server.StopMe
Set Server = Nothing
End Sub🛣️ 路由相关方法(通过 Router 对象)
Reg
注册控制器。
Public Function Reg(ControllerName As String, Controller As Object) As Boolean参数:
ControllerName- 控制器名称Controller- 控制器对象实例
示例:
' 注册控制器
Call Server.Router.Reg("User", New cUserController)
Call Server.Router.Reg("Api", New cApiController)Add
添加路由规则。
Public Function Add(RouteName As String, Handler As String, Optional MethodLimit As EnumRouteMethod = Any_) As Boolean参数:
RouteName- 路由路径(如 "/user")Handler- 处理程序(格式:"控制器名@方法名")MethodLimit- HTTP 方法限制:Any_- 任意方法(默认)OnlyGet- 仅 GETOnlyPost- 仅 POSTOnlyPut- 仅 PUTOnlyDelete- 仅 DELETE
示例:
' 基本路由
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)📡 事件
OnAccept
新连接接入时触发。
Public Event OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)参数:
ClientInfo- 客户端信息对象Disconnect- 设置为 True 可拒绝连接
示例:
Private Sub Server_OnAccept(ClientInfo As cHttpServerClientInfo, Disconnect As Boolean)
Debug.Print "新连接: " & ClientInfo.IP & ":" & ClientInfo.Port
' IP 黑名单检查
If ClientInfo.IP = "192.168.1.100" Then
Disconnect = True ' 拒绝连接
End If
End SubOnLogs
日志事件。
Public Event OnLogs(ByVal Level As String, ByVal Content As String)示例:
Private Sub Server_OnLogs(ByVal Level As String, ByVal Content As String)
Debug.Print "[" & Level & "] " & Content
End Sub🔒 连接管理
MaxConnections
最大并发连接数。
Public MaxConnections As Long默认值: 1000
说明: 当连接数达到此上限时,新连接将被拒绝(Disconnect = True)。建议根据服务器内存和业务需求调整。
示例:
Server.MaxConnections = 500 ' 启动前设置MaxRequestSize
最大请求体字节数。
Public MaxRequestSize As Long默认值: 10485760 (10MB)
说明: 当请求体超过此大小时,连接将被断开并返回 413 状态码。设为 0 表示不限制(不推荐)。
示例:
Server.MaxRequestSize = 5242880 ' 5MBIdleTimeoutSeconds
空闲连接超时秒数。
Public IdleTimeoutSeconds As Long默认值: 120
说明: 客户端在此时间内没有发送数据,服务端将主动关闭连接并释放资源。设为 0 表示不检测空闲连接(不推荐用于生产环境)。服务器内置定时器默认每 30 秒自动清理空闲连接,无需外部定时器。也可手动调用 CleanupIdleConnections()。
示例:
Server.IdleTimeoutSeconds = 60 ' 1 分钟ConnectionCount
当前活跃连接数(只读)。
Public Property Get ConnectionCount() As Long示例:
Debug.Print "当前连接数: " & Server.ConnectionCountCleanupIdleConnections
手动清理空闲连接。
Public Sub CleanupIdleConnections()说明: 遍历连接池,关闭超过 IdleTimeoutSeconds 未活动的连接,断开循环引用并释放资源。
服务器启动后内置定时器会自动定期调用此方法,通常无需手动调用。
示例:
' 手动触发清理(通常不需要,内置定时器已自动处理)
Call Server.CleanupIdleConnections
Debug.Print "连接数: " & Server.ConnectionCountCleanupExpiredSessions
手动清理过期的 Session。
Public Sub CleanupExpiredSessions()说明: 根据存储类型清理过期 Session:
- 内存模式:遍历 Session 字典,删除过期项并释放资源
- 文件模式:扫描 Session 目录,删除过期 JSON 文件
- 数据库模式:执行 DELETE 语句删除过期记录
服务器启动后内置定时器会自动定期调用此方法,通常无需手动调用。
示例:
' 手动触发清理(通常不需要,内置定时器已自动处理)
Call Server.CleanupExpiredSessionsCleanupTimerInterval
内置清理定时器间隔(毫秒)。
Public Property Get CleanupTimerInterval() As Long
Public Property Let CleanupTimerInterval(ByVal value As Long)默认值: 30000 (30 秒)
说明: 服务器启动后自动创建定时器,每隔此时间自动执行 CleanupIdleConnections 和 CleanupExpiredSessions。设为 0 可禁用内置定时器(不推荐)。服务器运行中修改间隔会自动重启定时器生效。
示例:
Server.CleanupTimerInterval = 15000 ' 15 秒清理一次
' 服务器运行中也可以修改,立即生效
Server.CleanupTimerInterval = 60000 ' 改为 60 秒📄 默认文档配置
AddDefaultDocument
添加自定义默认文档。
Public Sub AddDefaultDocument(FileName As String)参数:
FileName- 默认文档文件名(如 "home.html")
说明: 在 Start 前调用。内置默认文档列表为 index.html → index.htm → default.html → default.htm,自定义文档追加到列表末尾。重复添加会自动忽略。
示例:
Server.AddDefaultDocument "home.html"
Server.AddDefaultDocument "start.html"
Server.WebRoot("C:\WebRoot").Start 8080
' 查找顺序: index.html → index.htm → default.html → default.htm → home.html → start.html💾 静态文件缓存
MaxCacheFileSize
单文件缓存上限(字节)。
Public Property Get MaxCacheFileSize() As Long
Public Property Let MaxCacheFileSize(ByVal value As Long)默认值: 1048576 (1MB)
说明: 静态文件内容缓存的单文件大小上限。首次访问且文件大小 ≤ 此上限时自动加入内存缓存(懒缓存机制)。超出此上限的文件始终从磁盘读取,但仍享受 ETag/304 协商缓存。设为 0 可禁用内容缓存。可在 Start 前或运行中随时修改。
示例:
Server.MaxCacheFileSize = 2097152 ' 2MB
Server.MaxCacheFileSize = 0 ' 禁用内容缓存(仅保留ETag/304)CacheTTLSeconds
缓存 TTL(秒)。
Public Property Get CacheTTLSeconds() As Long
Public Property Let CacheTTLSeconds(ByVal value As Long)默认值: 300 (5 分钟)
说明: 缓存条目的存活时间。过期后不会立即删除,而是下次访问时检查 ETag 是否变化再决定刷新或续期。设为 0 表示永不过期(仅通过 ETag 感知文件更新)。可在 Start 前或运行中随时修改。
示例:
Server.CacheTTLSeconds = 600 ' 10 分钟
Server.CacheTTLSeconds = 0 ' 永不过期RefreshCache
刷新目录结构缓存。
Public Sub RefreshCache()说明: 部署新文件/新目录到 WebRoot 后手动调用,刷新服务器的目录结构缓存(rootFiles/rootDirs)。不影响文件内容缓存,内容缓存通过 ETag 自动感知文件更新。
示例:
' 部署新文件后刷新
Server.RefreshCacheClearFileCache
清空所有文件内容缓存。
Public Sub ClearFileCache()说明: 强制清空所有内存中的文件内容缓存,下次访问时重新从磁盘读取。适用于需要强制释放内存的场景。大多数情况下只需 RefreshCache,内容缓存会通过 ETag 自动感知文件更新。
示例:
' 强制清空内容缓存
Server.ClearFileCache📊 性能统计(Statistics)
Statistics 对象
cHttpServerStatistics 是服务器级性能统计容器,通过 Server.Statistics 或 ctx.Statistics 访问。所有字段为 Public Long,递增操作零开销。
Public Statistics As cHttpServerStatistics请求统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
TotalRequests | Long | 累计请求总数 |
GetRequests | Long | GET 请求数 |
PostRequests | Long | POST 请求数 |
PutRequests | Long | PUT 请求数 |
DeleteRequests | Long | DELETE 请求数 |
OptionsRequests | Long | OPTIONS 请求数 |
HeadRequests | Long | HEAD 请求数 |
PatchRequests | Long | PATCH 请求数 |
OtherRequests | Long | 其他方法请求数 |
状态码统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
Status1xx | Long | 1xx 响应数 |
Status2xx | Long | 2xx 响应数 |
Status3xx | Long | 3xx 响应数 |
Status4xx | Long | 4xx 响应数 |
Status5xx | Long | 5xx 响应数 |
连接统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
TotalConnectionsAccepted | Long | 累计接受连接总数 |
RejectedConnections | Long | 因 MaxConnections 被拒绝的连接数 |
PeakConnections | Long | 峰值并发连接数 |
IdleConnectionsCleaned | Long | 因空闲超时被清理的连接数 |
错误统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
RequestErrors | Long | 请求处理异常次数 |
RequestSizeRejected | Long | 413 Payload Too Large 次数 |
SSEEntryErrors | Long | SSE Entry 失败次数 |
流量统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
TotalBytesReceived | Long | 累计接收字节数 |
TotalBytesSent | Long | 累计发送字节数 |
SSE/Session/时间统计字段:
| 字段 | 类型 | 说明 |
|---|---|---|
SSEConnectionsAccepted | Long | SSE 连接总数 |
TotalSessionsCreated | Long | 累计创建的 Session 总数 |
StartTime | Date | 服务器启动时间 |
计算属性:
| 属性 | 类型 | 说明 |
|---|---|---|
UptimeSeconds | Long (Property Get) | 服务器运行时长(秒) |
AverageQPS | Double (Property Get) | 每秒平均请求数 |
方法:
| 方法 | 说明 |
|---|---|
Reset() | 重置所有统计计数器,StartTime 重置为 Now |
示例:
' 在控制器中读取统计
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
' 也可以通过 Server 直接访问
Debug.Print "Total: " & Server.Statistics.TotalRequests
Debug.Print "QPS: " & Server.Statistics.AverageQPS
' 重置统计
Server.Statistics.Reset🔧 控制器方法编写规范
控制器方法接收一个上下文参数,包含请求和响应对象:
Public Sub ActionName(ctx As cHttpServerContext)
' ctx.Request - 请求对象
' ctx.Response - 响应对象
' ctx.Session - Session 对象
' ctx.Cookies - Cookies 对象
' ctx.Db - 数据库对象(如果配置了)
End Sub示例控制器:
' cUserController.cls
Option Explicit
' GET /user
Public Sub List(ctx As cHttpServerContext)
Dim users As New Dictionary
users("items") = Array("张三", "李四", "王五")
users("total") = 3
ctx.Response.Json users, 0, "Success"
End Sub
' POST /user/create
Public Sub Create(ctx As cHttpServerContext)
' 获取 POST 数据
Dim username As String
username = ctx.Request.Form("username")
' 获取 JSON 数据
' username = ctx.Request.Json.GetItem("username")
ctx.Response.Json Nothing, 0, "创建成功"
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") = "张三"
ctx.Response.Json user
End Sub📦 上下文对象属性
cHttpServerContext
| 属性 | 类型 | 说明 |
|---|---|---|
Request | cHttpServerRequest | 请求对象 |
Response | cHttpServerResponse | 响应对象 |
Session | cHttpServerSession | Session 对象 |
Cookies | cHttpServerCookies | Cookies 对象 |
Db | cDataBase | 数据库对象 |
Server | cHttpServerSvr | 服务器配置 |
ClientInfo | cHttpServerClientInfo | 客户端信息 |
Statistics | cHttpServerStatistics | 性能统计对象(服务器级单例引用) |
最后更新: 2026-06-22