WebSocket Class Library Overview
📋 Library Components
Public Classes (Direct User Use)
| Class Name | File | Purpose |
|---|---|---|
cWebSocketClient | cWebSocketClient.cls | WebSocket client implementation |
cWebSocketServer | cWebSocketServer.cls | WebSocket server implementation |
Helper Classes (Internal Use)
| Class Name | File | Purpose |
|---|---|---|
cWebSocketServerClient | cWebSocketServerClient.cls | Server client connection management |
cWebSocketFrame | cWebSocketFrame.cls | WebSocket frame parsing and building |
cByteBuffer | cByteBuffer.cls | Efficient byte buffer management |
Utility Modules (Public)
| Module Name | File | Purpose |
|---|---|---|
mWebSocketUtils | mWebSocketUtils.bas | Common utility functions (UTF-8, Base64, SHA1, etc.) |
📦 Library Structure
newWebsocket/
├── mWebSocketUtils.bas # Common utility module
├── cByteBuffer.cls # Efficient byte buffer
├── cWebSocketFrame.cls # WebSocket frame parser
├── cWebSocketClient.cls # WebSocket client
├── cWebSocketServer.cls # WebSocket server
└── cWebSocketServerClient.cls # Server client connection🎯 Core Design Philosophy
1. Responsibility Separation
Each class handles a single function for easy maintenance and debugging:
- cWebSocketClient - Handles only client logic (connection, sending, receiving)
- cWebSocketServer - Handles only server logic (listening, client management, broadcasting)
- cWebSocketFrame - Handles only frame parsing and building
- cByteBuffer - Handles only byte buffer management
2. Read-Only Parsing
cWebSocketFrame.ParseHeader() does not modify input data, avoiding buffer confusion:
vb
' Clear process flow, distinct steps
1. ParseHeader(buffer) - Parse header (read-only)
2. IsCompleteFrame(buffer) - Check completeness
3. ExtractPayload(buffer) - Extract and unmask (consume buffer)3. Efficient Buffering
cByteBuffer uses pre-allocation strategy:
- Initial capacity: 4KB
- Growth factor: 1.5x
- Minimize ReDim Preserve calls
4. Automatic Handshake
- Client: Automatically generates WebSocket Key, sends handshake request, verifies response
- Server: Automatically detects Upgrade request, calculates Accept Key, sends response
5. Event-Driven
All operations are notified through events, no polling needed:
- Connection established →
OnOpen - Message received →
OnTextMessage/OnBinaryMessage - Connection closed →
OnClose - Error occurred →
OnError
🔄 Connection State Machine
Client States (WsState)
WS_STATE_CLOSED (0)
↓ Connect()
WS_STATE_CONNECTING (1)
↓ Handshake successful
WS_STATE_OPEN (2)
↓ Close()
WS_STATE_CLOSING (3)
↓ Close complete
WS_STATE_CLOSED (0)Server Client States (WsClientState)
WS_CLIENT_PENDING (0)
↓ Handshake successful
WS_CLIENT_CONNECTED (1)
↓ SendClose()
WS_CLIENT_CLOSING (2)
↓ Close complete
(Object removed)📨 WebSocket Frame
Frame Structure
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |K| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+Frame Types (WsOpCode)
| OpCode | Name | Description |
|---|---|---|
| 0 | CONTINUATION | Continuation frames for fragmented messages |
| 1 | TEXT | Text data frame |
| 2 | BINARY | Binary data frame |
| 8 | CLOSE | Connection close frame |
| 9 | PING | Ping frame (keepalive) |
| 10 | PONG | Pong frame (response) |
Close Codes (WsCloseCode)
| Code | Name | Description |
|---|---|---|
| 1000 | NORMAL | Normal closure |
| 1001 | GOING_AWAY | Endpoint going away |
| 1002 | PROTOCOL_ERROR | Protocol error |
| 1003 | UNSUPPORTED_DATA | Unsupported data type |
| 1006 | ABNORMAL | Abnormal closure (local) |
| 1007 | INVALID_DATA | Invalid data |
| 1008 | POLICY_VIOLATION | Policy violation |
| 1009 | MESSAGE_TOO_BIG | Message too large |
| 1011 | INTERNAL_ERROR | Internal error |
🚀 Performance Characteristics
Memory Efficiency
- Pre-allocated buffers: Reduces frequent memory allocation
- Smart growth: 1.5x growth factor balances space and performance
- Timely release: Automatically cleans resources when connection closes
CPU Efficiency
- Batch processing: Parses multiple frames at once
- Minimal copying: Uses CopyMemory API
- Async processing: Does not block the main thread
Network Efficiency
- Auto-fragmentation: Large messages are automatically fragmented
- Prompt response: Ping/Pong responded promptly
- Batch broadcasting: Broadcast messages built once, sent multiple times
🛡️ Security Features
Handshake Verification
- WebSocket Key verification: Prevents cross-site WebSocket hijacking
- Protocol version check: Ensures compatible version is used
- HTTP header parsing: Strictly verifies Upgrade requests
Data Masking
- Client masking: All frames sent by client are masked
- Server no masking: Frames sent by server are not masked (per RFC 6455)
Error Handling
- Unified error reporting: All errors through OnError event
- Auto-close: Protocol errors automatically close connection
- Detailed status codes: Detailed status code and reason provided on close
📊 Comparison with Old Library
| Feature | Old Version | New Version |
|---|---|---|
| Client/Server | Mixed in one class | Separated into independent classes |
| Frame Parsing | Modifies input data | Read-only parsing |
| Buffer Management | Dynamic allocation | Pre-allocation + growth |
| Responsibility Separation | Unclear | Clearly separated |
| Debugging Difficulty | Higher | Lower |
| Code Maintainability | Average | Excellent |
📝 Use Cases
Real-time Chat Application
vb
' Client connects to chat server
m_Client.Connect "ws://chat.example.com:8080"
' Send chat message
m_Client.SendText "Hello everyone!"
' Receive chat message (event-driven)
Private Sub m_Client_OnTextMessage(ByVal Message As String)
DisplayMessage Message
End SubReal-time Data Push
vb
' Server pushes data to all clients
Private Sub Timer1_Timer()
Dim sData As String
sData = GetLatestData()
m_Server.BroadcastText sData
End SubOnline Games
vb
' Send game action (binary)
Dim baData() As Byte
baData = SerializeGameAction()
m_Client.SendBinary baData
' Receive other players' actions
Private Sub m_Client_OnBinaryMessage(Data() As Byte)
ProcessGameAction Data
End SubDevice Control
vb
' Send control command
m_Server.SendText ClientID, "TURN_ON"
' Receive device status
Private Sub m_Server_OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)
UpdateDeviceStatus ClientID, Message
End Sub🔧 Extensibility
Adding Custom Sub-Protocols
vb
' Specify sub-protocol during handshake
m_Client.Connect "ws://example.com:8080", "chat.v1"Adding Custom HTTP Headers
vb
' Extend SendHandshake method to add custom headers
' Note: Requires modification inside the classCustom Frame Processing
vb
' Inherit cWebSocketFrame class to add custom frame types
' Or modify ProcessReceivedData method⚠️ Known Limitations
- No wss:// support: SSL/TLS requires additional implementation
- No compression: WebSocket compression extension not implemented
- Single-threaded model: All operations run on the main thread
- Max message size: Limited by VB6 array size (approx 2GB)
Last Updated: 2026-01-10