cWebSocketClient Class Reference
📋 Class Overview
cWebSocketClient is a WebSocket client implementation class that provides functionality to connect to WebSocket servers, send/receive messages, and handle automatic handshakes.
📡 Event List
| Event Name | Trigger Timing | Parameters |
|---|---|---|
OnOpen | Connection successfully established | None |
OnClose | Connection closed | Code (Close code), Reason (Close reason) |
OnTextMessage | Text message received | Message (Message content) |
OnBinaryMessage | Binary message received | Data() (Byte array) |
OnError | Error occurred | Description (Error description) |
OnPong | Pong response received | Data() (Pong payload) |
🔧 Property Reference
State - Connection State
Type: WsState (Enum)
Read/Write: Read-only
Values:
| Constant | Value | Description |
|---|---|---|
WS_STATE_CLOSED | 0 | Closed |
WS_STATE_CONNECTING | 1 | Connecting/handshaking |
WS_STATE_OPEN | 2 | Connected, can send messages |
WS_STATE_CLOSING | 3 | Closing |
Example:
If m_Client.State = WS_STATE_OPEN Then
m_Client.SendText "Hello"
Else
Debug.Print "Not connected"
End IfURL - Connection URL
Type: String
Read/Write: Read-only
Description: The current or last connected WebSocket URL.
Example:
Debug.Print "Connected to: " & m_Client.URL
' Output: Connected to: ws://127.0.0.1:8080Host - Server Hostname
Type: String
Read/Write: Read-only
Description: Server hostname or IP address parsed from URL.
Example:
Debug.Print "Server: " & m_Client.HostPort - Server Port
Type: Long
Read/Write: Read-only
Description: Server port number parsed from URL.
Example:
Debug.Print "Port: " & m_Client.PortAutoPing - Auto Ping
Type: Boolean
Read/Write: Read/Write
Description: Whether to enable automatic Ping (keepalive feature). Default is False.
Example:
' Enable auto Ping
m_Client.AutoPing = True
' Disable auto Ping
m_Client.AutoPing = FalsePingInterval - Ping Interval
Type: Long
Read/Write: Read/Write
Description: Auto Ping interval time in milliseconds. Default is 30000 (30 seconds).
Example:
' Set Ping interval to 20 seconds
m_Client.PingInterval = 20000🚀 Method Reference
Connect - Connect to Server
Syntax:
Public Sub Connect(ByVal WebSocketURL As String, Optional ByVal SubProtocol As String = "")Parameters:
| Parameter | Type | Description |
|---|---|---|
WebSocketURL | String | WebSocket server URL, format: ws[s]://host[:port][/path][?query] |
SubProtocol | String (Optional) | WebSocket sub-protocol |
URL Format:
- Standard format:
ws://example.com:8080/chat - Default port:
ws://example.com/chat(default 80) - Query parameters:
ws://example.com/chat?token=abc123 - Secure connection:
wss://example.com(not yet implemented)
Example:
' Basic connection
m_Client.Connect "ws://127.0.0.1:8080"
' Connection with path
m_Client.Connect "ws://example.com/chat"
' Connection with query parameters
m_Client.Connect "ws://example.com/chat?token=abc123"
' Specify sub-protocol
m_Client.Connect "ws://example.com/chat", "chat.v1"Error Handling:
Private Sub cmdConnect_Click()
On Error GoTo EH
m_Client.Connect "ws://example.com:8080"
Exit Sub
EH:
Debug.Print "Connection failed: " & Err.Description
End SubCloseConnection - Close Connection
Syntax:
Public Sub CloseConnection(Optional ByVal Code As WsCloseCode = WS_CLOSE_NORMAL, _
Optional ByVal Reason As String = "")Parameters:
| Parameter | Type | Description |
|---|---|---|
Code | WsCloseCode (Optional) | Close status code, default WS_CLOSE_NORMAL |
Reason | String (Optional) | Close reason |
Common Close Codes:
m_Client.CloseConnection WS_CLOSE_NORMAL, "Normal closure"
m_Client.CloseConnection WS_CLOSE_GOING_AWAY, "User leaving"
m_Client.CloseConnection WS_CLOSE_PROTOCOL_ERROR, "Protocol error"Example:
' Normal close
m_Client.CloseConnection
' Specify close code and reason
m_Client.CloseConnection WS_CLOSE_GOING_AWAY, "User logout"
' Auto disconnect on form close
Private Sub Form_Unload(Cancel As Integer)
m_Client.CloseConnection WS_CLOSE_GOING_AWAY, "Application closing"
End SubSendText - Send Text Message
Syntax:
Public Sub SendText(ByVal Message As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
Message | String | Text message to send |
Description: Message is automatically converted to UTF-8 encoding and WebSocket frame header is added. Frames sent by client are automatically masked.
Example:
' Send simple text
m_Client.SendText "Hello WebSocket!"
' Send JSON data
Dim sJSON As String
sJSON = "{""type"":""message"", ""content"":""Hello""}"
m_Client.SendText sJSON
' Send multi-line text
m_Client.SendText "First line" & vbCrLf & "Second line"Error Handling:
On Error GoTo EH
m_Client.SendText "Hello"
Exit Sub
EH:
Debug.Print "Send failed: " & Err.DescriptionSendBinary - Send Binary Message
Syntax:
Public Sub SendBinary(Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Binary data to send |
Example:
' Send byte array
Dim baData() As Byte
baData = StringToBytes("Hello")
m_Client.SendBinary baData
' Send image data
Dim baImage() As Byte
baImage = LoadImageToByteArray()
m_Client.SendBinary baImage
' Send serialized object
Dim baObj() As Byte
baObj = SerializeObject(myObject)
m_Client.SendBinary baObjSendPing - Send Ping Frame
Syntax:
Public Sub SendPing(Optional Payload As Variant)Parameters:
| Parameter | Type | Description |
|---|---|---|
Payload | Variant (Optional) | Ping payload, can be string or byte array |
Description: Used for connection keepalive, server automatically replies with Pong frame.
Example:
' Send empty Ping (keepalive)
m_Client.SendPing
' Send Ping with data
m_Client.SendPing "ping"
' Send Ping with binary data
Dim baData() As Byte
baData = StringToUTF8("ping")
m_Client.SendPing baData
' Measure latency
Dim lStartTime As Long
lStartTime = GetTickCount()
m_Client.SendPing "ping"
Private Sub m_Client_OnPong(Data() As Byte)
Dim lElapsed As Long
lElapsed = GetTickCount() - lStartTime
Debug.Print "Latency: " & lElapsed & " ms"
End Sub📡 Event Details
OnOpen - Connection Opened
Syntax:
Event OnOpen()Description: Triggered after WebSocket handshake successful, now you can start sending messages.
Example:
Private Sub m_Client_OnOpen()
Debug.Print "Successfully connected to WebSocket server"
' Send welcome message
m_Client.SendText "Hello Server!"
' Update UI
lblStatus.Caption = "Connected"
cmdSend.Enabled = True
End SubOnClose - Connection Closed
Syntax:
Event OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
Code | WsCloseCode | Close status code |
Reason | String | Close reason |
Example:
Private Sub m_Client_OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)
Debug.Print "Connection closed"
Debug.Print "Status code: " & Code
Debug.Print "Reason: " & Reason
' Handle based on close code
Select Case Code
Case WS_CLOSE_NORMAL
Debug.Print "Normal closure"
Case WS_CLOSE_ABNORMAL
Debug.Print "Abnormal closure"
' Try to reconnect
If m_bAutoReconnect Then
tmrReconnect.Enabled = True
End If
Case WS_CLOSE_GOING_AWAY
Debug.Print "Server closed"
Case Else
Debug.Print "Other reason: " & Reason
End Select
' Update UI
lblStatus.Caption = "Disconnected"
cmdSend.Enabled = False
End SubOnTextMessage - Text Message Received
Syntax:
Event OnTextMessage(ByVal Message As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
Message | String | Received text message (UTF-8 decoded) |
Example:
Private Sub m_Client_OnTextMessage(ByVal Message As String)
Debug.Print "Received message: " & Message
' Handle JSON message
If Left$(Message, 1) = "{" Then
Dim sType As String
sType = GetJSONField(Message, "type")
Select Case sType
Case "chat"
DisplayChatMessage Message
Case "notification"
DisplayNotification Message
End Select
Else
' Simple text message
txtMessages.Text = txtMessages.Text & Message & vbCrLf
End If
End SubOnBinaryMessage - Binary Message Received
Syntax:
Event OnBinaryMessage(Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Received binary data |
Example:
Private Sub m_Client_OnBinaryMessage(Data() As Byte)
Debug.Print "Received binary message: " & (UBound(Data) + 1) & " bytes"
' Check data type (assume first 4 bytes are type identifier)
If UBound(Data) >= 3 Then
Dim lType As Long
lType = CLng(Data(0)) * 256& ^ 3 + CLng(Data(1)) * 256& ^ 2 + _
CLng(Data(2)) * 256& + CLng(Data(3))
Select Case lType
Case 1 ' Text
Dim sText As String
sText = UTF8ToString(ExtractData(Data, 4))
Debug.Print "Text data: " & sText
Case 2 ' Image
DisplayImage ExtractData(Data, 4)
Case 3 ' Custom
ProcessCustomData ExtractData(Data, 4)
End Select
End If
End SubOnError - Error Occurred
Syntax:
Event OnError(ByVal Description As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
Description | String | Error description |
Example:
Private Sub m_Client_OnError(ByVal Description As String)
Debug.Print "Error: " & Description
' Show error alert
MsgBox "Error occurred: " & Description, vbExclamation
' Log error
LogError Description
' Update UI
lblStatus.Caption = "Error"
End SubOnPong - Pong Received
Syntax:
Event OnPong(Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Pong payload (corresponds to Ping data) |
Description: Usually used for measuring network latency or confirming connection activity.
Example:
Private m_lPingTimes() As Long
Private m_lPingIndex As Long
Private Sub SendPingForLatency()
ReDim m_lPingTimes(1) As Long
m_lPingIndex = 0
m_lPingTimes(0) = GetTickCount()
m_Client.SendPing "ping"
End Sub
Private Sub m_Client_OnPong(Data() As Byte)
m_lPingTimes(1) = GetTickCount()
Dim lLatency As Long
lLatency = m_lPingTimes(1) - m_lPingTimes(0)
Debug.Print "Network latency: " & lLatency & " ms"
' Update UI
lblLatency.Caption = lLatency & " ms"
End Sub📝 Complete Example
Basic Client Example
Private WithEvents m_Client As cWebSocketClient
Private Sub Form_Load()
Set m_Client = New cWebSocketClient
End Sub
Private Sub cmdConnect_Click()
m_Client.Connect "ws://127.0.0.1:8080"
End Sub
Private Sub cmdSend_Click()
m_Client.SendText txtMessage.Text
End Sub
Private Sub cmdDisconnect_Click()
m_Client.CloseConnection
End Sub
Private Sub m_Client_OnOpen()
Debug.Print "Connected"
cmdSend.Enabled = True
End Sub
Private Sub m_Client_OnTextMessage(ByVal Message As String)
txtLog.Text = txtLog.Text & Message & vbCrLf
End Sub
Private Sub m_Client_OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)
Debug.Print "Disconnected: " & Reason
cmdSend.Enabled = False
End SubClient with Reconnect
Private WithEvents m_Client As cWebSocketClient
Private m_bAutoReconnect As Boolean
Private m_sServerURL As String
Private Sub Form_Load()
Set m_Client = New cWebSocketClient
m_bAutoReconnect = True
m_sServerURL = "ws://127.0.0.1:8080"
ConnectToServer
End Sub
Private Sub ConnectToServer()
If m_Client.State = WS_STATE_CLOSED Then
Debug.Print "Connecting..."
m_Client.Connect m_sServerURL
End If
End Sub
Private Sub m_Client_OnOpen()
Debug.Print "Connected"
tmrReconnect.Enabled = False
End Sub
Private Sub m_Client_OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)
Debug.Print "Connection closed: " & Reason
If m_bAutoReconnect Then
Debug.Print "Reconnecting in 3 seconds..."
tmrReconnect.Interval = 3000
tmrReconnect.Enabled = True
End If
End Sub
Private Sub tmrReconnect_Timer()
tmrReconnect.Enabled = False
ConnectToServer
End SubLast Updated: 2026-01-10