VBMAN SSE (Server-Sent Events) Server Push Example
Overview
This example demonstrates how to implement SSE (Server-Sent Events) server push functionality using the VBMAN framework, enabling real-time data push from server to client. The example includes both timed push and manual push modes.
Project Structure
SSE/
├── src/ # Server-side project
│ ├── Form1.frm # Main form
│ ├── bMes.cls # Message handling class
│ └── VBMAN_DEMO_SSE.vbp # Project file
└── www/ # Frontend pages
└── Client.html # SSE client page
Core Code Analysis
1. Server Configuration (Form1.frm)
vb
Dim HttpServer As New VBMANLIB.cHttpServer
Private Sub Form_Load()
With HttpServer
.Router.Reg "Mes", New bMes 'Register message handling class
.Router.AutoRoute = True 'Enable auto routing
.CrossDomain.Enable = True 'Allow cross-domain access
'Enable SSE functionality
.SSE.Start
'Start Web server
.Start 82, App.Path & "\..\www"
End With
Shell "explorer http://127.0.0.1:82/Client.html"
End Sub
'Timer push
Private Sub Timer1_Timer()
HttpServer.SSE.SendPack "timer", Now()
End Sub
'Manual push
Private Sub Command1_Click()
HttpServer.SSE.SendPack "test", Text2.Text
End Sub
2. Message Handling Class (bMes.cls)
vb
Public Sub Printer(ctx As VBMANLIB.cHttpServerContext)
'Get data sent from client
Dim zs As String: zs = ctx.Request.Json.Root("data")(1)("name")
Dim ls As String: ls = ctx.Request.Json.Root("data")(2)("name")
'Display data on interface
Form1.Text1.Text = ctx.Request.Json.Encode(, 2)
'Respond to client
ctx.Response.Text "Processing successful: " & Now()
End Sub
3. Client Implementation (Client.html)
html
<script>
// Create SSE connection
var source = new EventSource('/sse');
// Listen for server messages
source.addEventListener('timer', function(e) {
console.log('Timed message:', e.data);
});
source.addEventListener('test', function(e) {
console.log('Test message:', e.data);
});
// Connection success callback
source.onopen = function() {
console.log('SSE connection established');
};
// Error handling
source.onerror = function(e) {
console.log('SSE connection error:', e);
};
</script>
Feature Description
SSE Server Features
- Support for multiple client connections
- Support for timed push
- Support for manual push
- Support for custom event types
Message Push Features
- Automatic reconnection mechanism
- Disconnect reconnection
- Event categorized push
- Cross-domain support
Client Features
- Native SSE support
- Event listening mechanism
- Connection status monitoring
- Error handling
Technical Points
- SSE protocol implementation
- Real-time data push
- Long connection management
- Event-driven model
Use Cases
- Real-time data monitoring
- Message notification system
- Real-time report updates
- Live log display
Extension Suggestions
- Add message filtering mechanism
- Implement message compression
- Add message priority
- Implement message confirmation mechanism
- Add load balancing support