mWebSocketUtils Utility Module Reference
📋 Module Overview
mWebSocketUtils is the public utility module for the WebSocket class library, providing the following functionality:
- UTF-8 encoding/decoding
- Base64 encoding
- SHA1 hash calculation
- WebSocket Key generation and verification
- HTTP header parsing
- Close code description retrieval
📊 Public Enums
WsOpCode - WebSocket Operation Codes
Public Enum WsOpCode
WS_OPCODE_CONTINUATION = 0 ' Continuation frames for fragmented messages
WS_OPCODE_TEXT = 1 ' Text data frame
WS_OPCODE_BINARY = 2 ' Binary data frame
WS_OPCODE_CLOSE = 8 ' Connection close frame
WS_OPCODE_PING = 9 ' Ping frame
WS_OPCODE_PONG = 10 ' Pong frame
End EnumWsCloseCode - WebSocket Close Status Codes
Public Enum WsCloseCode
WS_CLOSE_NORMAL = 1000 ' Normal closure
WS_CLOSE_GOING_AWAY = 1001 ' Endpoint going away
WS_CLOSE_PROTOCOL_ERROR = 1002 ' Protocol error
WS_CLOSE_UNSUPPORTED_DATA = 1003 ' Unsupported data type
WS_CLOSE_NO_STATUS = 1005 ' No status (local)
WS_CLOSE_ABNORMAL = 1006 ' Abnormal closure (local)
WS_CLOSE_INVALID_DATA = 1007 ' Invalid data
WS_CLOSE_POLICY_VIOLATION = 1008 ' Policy violation
WS_CLOSE_MESSAGE_TOO_BIG = 1009 ' Message too large
WS_CLOSE_MANDATORY_EXT = 1010 ' Mandatory extension
WS_CLOSE_INTERNAL_ERROR = 1011 ' Internal error
WS_CLOSE_SERVICE_RESTART = 1012 ' Service restart
WS_CLOSE_TRY_AGAIN = 1013 ' Try again later
End EnumWsState - WebSocket Connection State
Public Enum WsState
WS_STATE_CLOSED = 0 ' Closed
WS_STATE_CONNECTING = 1 ' Connecting
WS_STATE_OPEN = 2 ' Open
WS_STATE_CLOSING = 3 ' Closing
End Enum🔧 UTF-8 Functions
StringToUTF8 - String to UTF-8
Syntax:
Public Function StringToUTF8(ByVal Text As String) As Byte()Parameters:
| Parameter | Type | Description |
|---|---|---|
Text | String | String to convert |
Return Value: UTF-8 encoded byte array
Example:
' Simple conversion
Dim baUTF8() As Byte
baUTF8 = StringToUTF8("Hello WebSocket!")
' Chinese conversion
baUTF8 = StringToUTF8("你好世界")
' Empty string
baUTF8 = StringToUTF8("")
' Returns empty array
' For WebSocket sending
Dim sMessage As String
sMessage = "测试消息"
m_Client.SendText sMessage ' Internally calls StringToUTF8UTF8ToString - UTF-8 to String
Syntax:
Public Function UTF8ToString(ByRef Utf8Data() As Byte) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
Utf8Data() | Byte() | UTF-8 encoded byte array |
Return Value: Decoded string
Example:
' Decode UTF-8 data
Dim baData() As Byte
baData = LoadFile("utf8.txt")
Dim sText As String
sText = UTF8ToString(baData)
Debug.Print sText
' WebSocket message decoding
Private Sub m_Client_OnTextMessage(ByVal Message As String)
' Message is already decoded string
Debug.Print Message
End Sub
' Manual decoding
Dim sDecoded As String
sDecoded = UTF8ToString(baPayload)📦 Base64 Functions
Base64Encode - Base64 Encoding
Syntax:
Public Function Base64Encode(ByRef Data() As Byte) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Byte array to encode |
Return Value: Base64 encoded string
Description:
- Uses standard Base64 character set (A-Z, a-z, 0-9, +, /)
- Uses
=as padding character - Used for WebSocket handshake Key and Accept encoding
Example:
' Encode random data
Dim baData(15) As Byte
Randomize Timer
For i = 0 To 15
baData(i) = CByte(Int(Rnd * 256))
Next i
Dim sBase64 As String
sBase64 = Base64Encode(baData)
Debug.Print "Base64: " & sBase64
' Generate WebSocket Key
Dim sKey As String
sKey = GenerateWebSocketKey()
Debug.Print "WebSocket Key: " & sKey🔐 SHA1 Functions
SHA1Hash - Calculate SHA1 Hash
Syntax:
Public Function SHA1Hash(ByRef Data() As Byte) As Byte()Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Data to hash |
Return Value: 20-byte SHA1 hash value
Description:
- Uses Windows CryptoAPI
- Returns raw 20-byte hash value
Example:
' Calculate SHA1 hash
Dim baData() As Byte
baData = StringToUTF8("Hello World")
Dim baHash() As Byte
baHash = SHA1Hash(baData)
Dim sHashHex As String
sHashHex = BytesToHex(baHash)
Debug.Print "SHA1: " & sHashHex
' For WebSocket Accept Key calculation
Dim sCombined As String
sCombined = sClientKey & WS_MAGIC_GUID
Dim baCombined() As Byte
baCombined = StrConv(sCombined, vbFromUnicode)
Dim baHash() As Byte
baHash = SHA1Hash(baCombined)🔑 WebSocket Key Functions
GenerateWebSocketKey - Generate WebSocket Key
Syntax:
Public Function GenerateWebSocketKey() As StringReturn Value: Base64 encoded random 16-byte Key
Description:
- Used for client handshake
- Generates random 16 bytes
- Returns Base64 encoded result
Example:
' Client auto calls (internal use)
Dim sKey As String
sKey = GenerateWebSocketKey()
Debug.Print "WebSocket Key: " & sKey
' Output example: dGhlIHNhbXBsZSBub25jZQ==ComputeAcceptKey - Compute Accept Key
Syntax:
Public Function ComputeAcceptKey(ByVal ClientKey As String) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
ClientKey | String | WebSocket Key sent by client |
Return Value: Accept Key that server should return
Description:
- Calculates SHA1 hash of
ClientKey + WS_MAGIC_GUID - Base64 encodes the result
- Used for server handshake verification
Example:
' Server calculates Accept Key (internal use)
Dim sClientKey As String
sClientKey = GetHeaderValue(sHandshake, "Sec-WebSocket-Key")
Dim sAcceptKey As String
sAcceptKey = ComputeAcceptKey(sClientKey)
Debug.Print "Accept Key: " & sAcceptKey
' Output HTTP response header
Dim sResponse As String
sResponse = "HTTP/1.1 101 Switching Protocols" & vbCrLf
sResponse = sResponse & "Sec-WebSocket-Accept: " & sAcceptKey & vbCrLf
sResponse = sResponse & vbCrLfWS_MAGIC_GUID - WebSocket Magic GUID
Constant:
Public Const WS_MAGIC_GUID As String = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"Description: Fixed GUID used in WebSocket handshake for calculating Accept Key.
WS_VERSION - WebSocket Protocol Version
Constant:
Public Const WS_VERSION As String = "13"Description: WebSocket protocol version number (RFC 6455).
📋 HTTP Header Parsing Functions
GetHeaderValue - Get HTTP Header Value
Syntax:
Public Function GetHeaderValue(ByVal HttpText As String, ByVal HeaderName As String) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
HttpText | String | HTTP request/response text |
HeaderName | String | Header name (case-insensitive) |
Return Value: Header value, returns empty string if not found
Example:
' Get Host header
Dim sRequest As String
sRequest = "GET /chat HTTP/1.1" & vbCrLf
sRequest = sRequest & "Host: example.com:8080" & vbCrLf
sRequest = sRequest & "Upgrade: websocket" & vbCrLf
sRequest = sRequest & vbCrLf
Dim sHost As String
sHost = GetHeaderValue(sRequest, "Host")
Debug.Print "Host: " & sHost ' Output: example.com:8080
' Get WebSocket Key
Dim sKey As String
sKey = GetHeaderValue(sRequest, "Sec-WebSocket-Key")
' Get Connection header
Dim sConnection As String
sConnection = GetHeaderValue(sRequest, "Connection")📝 Close Code Description Functions
GetCloseCodeDescription - Get Close Code Description
Syntax:
Public Function GetCloseCodeDescription(ByVal Code As WsCloseCode) As StringParameters:
| Parameter | Type | Description |
|---|---|---|
Code | WsCloseCode | Close status code |
Return Value: Text description of the close code
Example:
Dim sDesc As String
sDesc = GetCloseCodeDescription(WS_CLOSE_NORMAL)
Debug.Print sDesc ' Output: Normal closure
sDesc = GetCloseCodeDescription(WS_CLOSE_ABNORMAL)
Debug.Print sDesc ' Output: Abnormal closure
sDesc = GetCloseCodeDescription(1000)
Debug.Print sDesc ' Output: Normal closure
sDesc = GetCloseCodeDescription(9999)
Debug.Print sDesc ' Output: Unknown (9999)
' Use in OnClose event
Private Sub m_Client_OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)
Debug.Print "Close code: " & Code
Debug.Print "Description: " & GetCloseCodeDescription(Code)
If LenB(Reason) > 0 Then
Debug.Print "Reason: " & Reason
End If
End Sub🧹 Cleanup Functions
CleanupCryptoProvider - Cleanup CryptoAPI Resources
Syntax:
Public Sub CleanupCryptoProvider()Description:
- Releases CryptoAPI context
- Usually called at program end
Example:
' Cleanup on program exit
Private Sub Form_Unload(Cancel As Integer)
CleanupCryptoProvider
End Sub📝 Complete Usage Examples
WebSocket Handshake Flow
' Client sends handshake request
Private Sub SendHandshake()
Dim sKey As String
sKey = GenerateWebSocketKey()
Dim sHandshake As String
sHandshake = "GET /chat HTTP/1.1" & vbCrLf
sHandshake = sHandshake & "Host: example.com:8080" & vbCrLf
sHandshake = sHandshake & "Upgrade: websocket" & vbCrLf
sHandshake = sHandshake & "Connection: Upgrade" & vbCrLf
sHandshake = sHandshake & "Sec-WebSocket-Key: " & sKey & vbCrLf
sHandshake = sHandshake & "Sec-WebSocket-Version: " & WS_VERSION & vbCrLf
sHandshake = sHandshake & vbCrLf
m_Socket.SendData sHandshake, ScpUtf8
End Sub
' Server handles handshake request
Private Function HandleHandshake(ByVal sRequest As String) As Boolean
' Get client Key
Dim sKey As String
sKey = GetHeaderValue(sRequest, "Sec-WebSocket-Key")
If LenB(sKey) = 0 Then
HandleHandshake = False
Exit Function
End If
' Calculate Accept Key
Dim sAccept As String
sAccept = ComputeAcceptKey(sKey)
' Send response
Dim sResponse As String
sResponse = "HTTP/1.1 101 Switching Protocols" & vbCrLf
sResponse = sResponse & "Upgrade: websocket" & vbCrLf
sResponse = sResponse & "Connection: Upgrade" & vbCrLf
sResponse = sResponse & "Sec-WebSocket-Accept: " & sAccept & vbCrLf
sResponse = sResponse & vbCrLf
m_Socket.SendData sResponse, ScpUtf8
HandleHandshake = True
End Function
' Client verifies handshake response
Private Function ValidateResponse(ByVal sResponse As String) As Boolean
' Check status code
If InStr(sResponse, "101") = 0 Then
ValidateResponse = False
Exit Function
End If
' Get Accept Key
Dim sAccept As String
sAccept = GetHeaderValue(sResponse, "Sec-WebSocket-Accept")
' Calculate expected value
Dim sExpected As String
sExpected = ComputeAcceptKey(m_sClientKey)
' Verify
ValidateResponse = (sAccept = sExpected)
End FunctionText Message Processing
' Send text message
Public Sub SendTextMessage(ByVal sText As String)
Dim baPayload() As Byte
baPayload = StringToUTF8(sText)
Dim oFrame As New cWebSocketFrame
Dim baFrame() As Byte
baFrame = oFrame.BuildFrame(baPayload, WS_OPCODE_TEXT, True, True)
m_Socket.SendData baFrame
End Sub
' Receive text message
Private Sub ProcessTextFrame(ByVal baPayload() As Byte)
Dim sText As String
sText = UTF8ToString(baPayload)
Debug.Print "Received text: " & sText
' Process message...
End SubCustom Data Processing
' Serialize object to UTF-8 JSON
Public Function SerializeJSON(ByVal oObject As Object) As Byte()
Dim sJSON As String
sJSON = ToJSONString(oObject)
Dim baData() As Byte
baData = StringToUTF8(sJSON)
SerializeJSON = baData
End Function
' Deserialize UTF-8 JSON to object
Public Function DeserializeJSON(ByVal baData() As Byte) As Object
Dim sJSON As String
sJSON = UTF8ToString(baData)
Set DeserializeJSON = FromJSONString(sJSON)
End Function⚠️ Notes
- CryptoAPI initialization - SHA1Hash automatically initializes CryptoAPI
- Resource cleanup - Call CleanupCryptoProvider at program end
- Encoding consistency - Both send and receive use UTF-8 encoding
- Case-insensitive header names - GetHeaderValue ignores case
Last Updated: 2026-01-10