Skip to content

WebSocket Class Library Overview ​

📋 Library Components ​

Public Classes (Direct User Use) ​

Class NameFilePurpose
cWebSocketClientcWebSocketClient.clsWebSocket client implementation
cWebSocketServercWebSocketServer.clsWebSocket server implementation

Helper Classes (Internal Use) ​

Class NameFilePurpose
cWebSocketServerClientcWebSocketServerClient.clsServer client connection management
cWebSocketFramecWebSocketFrame.clsWebSocket frame parsing and building
cByteBuffercByteBuffer.clsEfficient byte buffer management

Utility Modules (Public) ​

Module NameFilePurpose
mWebSocketUtilsmWebSocketUtils.basCommon 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) ​

OpCodeNameDescription
0CONTINUATIONContinuation frames for fragmented messages
1TEXTText data frame
2BINARYBinary data frame
8CLOSEConnection close frame
9PINGPing frame (keepalive)
10PONGPong frame (response)

Close Codes (WsCloseCode) ​

CodeNameDescription
1000NORMALNormal closure
1001GOING_AWAYEndpoint going away
1002PROTOCOL_ERRORProtocol error
1003UNSUPPORTED_DATAUnsupported data type
1006ABNORMALAbnormal closure (local)
1007INVALID_DATAInvalid data
1008POLICY_VIOLATIONPolicy violation
1009MESSAGE_TOO_BIGMessage too large
1011INTERNAL_ERRORInternal 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 ​

FeatureOld VersionNew Version
Client/ServerMixed in one classSeparated into independent classes
Frame ParsingModifies input dataRead-only parsing
Buffer ManagementDynamic allocationPre-allocation + growth
Responsibility SeparationUnclearClearly separated
Debugging DifficultyHigherLower
Code MaintainabilityAverageExcellent

📝 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 Sub

Real-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 Sub

Online 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 Sub

Device 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 class

Custom 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

VB6 and LOGO copyright of Microsoft Corporation