Skip to content

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 NameTrigger TimingParameters
OnOpenConnection successfully establishedNone
OnCloseConnection closedCode (Close code), Reason (Close reason)
OnTextMessageText message receivedMessage (Message content)
OnBinaryMessageBinary message receivedData() (Byte array)
OnErrorError occurredDescription (Error description)
OnPongPong response receivedData() (Pong payload)

🔧 Property Reference

State - Connection State

Type: WsState (Enum)
Read/Write: Read-only

Values:

ConstantValueDescription
WS_STATE_CLOSED0Closed
WS_STATE_CONNECTING1Connecting/handshaking
WS_STATE_OPEN2Connected, can send messages
WS_STATE_CLOSING3Closing

Example:

vb
If m_Client.State = WS_STATE_OPEN Then
    m_Client.SendText "Hello"
Else
    Debug.Print "Not connected"
End If

URL - Connection URL

Type: String
Read/Write: Read-only

Description: The current or last connected WebSocket URL.

Example:

vb
Debug.Print "Connected to: " & m_Client.URL
' Output: Connected to: ws://127.0.0.1:8080

Host - Server Hostname

Type: String
Read/Write: Read-only

Description: Server hostname or IP address parsed from URL.

Example:

vb
Debug.Print "Server: " & m_Client.Host

Port - Server Port

Type: Long
Read/Write: Read-only

Description: Server port number parsed from URL.

Example:

vb
Debug.Print "Port: " & m_Client.Port

AutoPing - Auto Ping

Type: Boolean
Read/Write: Read/Write

Description: Whether to enable automatic Ping (keepalive feature). Default is False.

Example:

vb
' Enable auto Ping
m_Client.AutoPing = True

' Disable auto Ping
m_Client.AutoPing = False

PingInterval - Ping Interval

Type: Long
Read/Write: Read/Write

Description: Auto Ping interval time in milliseconds. Default is 30000 (30 seconds).

Example:

vb
' Set Ping interval to 20 seconds
m_Client.PingInterval = 20000

🚀 Method Reference

Connect - Connect to Server

Syntax:

vb
Public Sub Connect(ByVal WebSocketURL As String, Optional ByVal SubProtocol As String = "")

Parameters:

ParameterTypeDescription
WebSocketURLStringWebSocket server URL, format: ws[s]://host[:port][/path][?query]
SubProtocolString (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:

vb
' 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:

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

CloseConnection - Close Connection

Syntax:

vb
Public Sub CloseConnection(Optional ByVal Code As WsCloseCode = WS_CLOSE_NORMAL, _
                          Optional ByVal Reason As String = "")

Parameters:

ParameterTypeDescription
CodeWsCloseCode (Optional)Close status code, default WS_CLOSE_NORMAL
ReasonString (Optional)Close reason

Common Close Codes:

vb
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:

vb
' 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 Sub

SendText - Send Text Message

Syntax:

vb
Public Sub SendText(ByVal Message As String)

Parameters:

ParameterTypeDescription
MessageStringText 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:

vb
' 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:

vb
On Error GoTo EH
m_Client.SendText "Hello"
Exit Sub
EH:
Debug.Print "Send failed: " & Err.Description

SendBinary - Send Binary Message

Syntax:

vb
Public Sub SendBinary(Data() As Byte)

Parameters:

ParameterTypeDescription
Data()Byte()Binary data to send

Example:

vb
' 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 baObj

SendPing - Send Ping Frame

Syntax:

vb
Public Sub SendPing(Optional Payload As Variant)

Parameters:

ParameterTypeDescription
PayloadVariant (Optional)Ping payload, can be string or byte array

Description: Used for connection keepalive, server automatically replies with Pong frame.

Example:

vb
' 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:

vb
Event OnOpen()

Description: Triggered after WebSocket handshake successful, now you can start sending messages.

Example:

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

OnClose - Connection Closed

Syntax:

vb
Event OnClose(ByVal Code As WsCloseCode, ByVal Reason As String)

Parameters:

ParameterTypeDescription
CodeWsCloseCodeClose status code
ReasonStringClose reason

Example:

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

OnTextMessage - Text Message Received

Syntax:

vb
Event OnTextMessage(ByVal Message As String)

Parameters:

ParameterTypeDescription
MessageStringReceived text message (UTF-8 decoded)

Example:

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

OnBinaryMessage - Binary Message Received

Syntax:

vb
Event OnBinaryMessage(Data() As Byte)

Parameters:

ParameterTypeDescription
Data()Byte()Received binary data

Example:

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

OnError - Error Occurred

Syntax:

vb
Event OnError(ByVal Description As String)

Parameters:

ParameterTypeDescription
DescriptionStringError description

Example:

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

OnPong - Pong Received

Syntax:

vb
Event OnPong(Data() As Byte)

Parameters:

ParameterTypeDescription
Data()Byte()Pong payload (corresponds to Ping data)

Description: Usually used for measuring network latency or confirming connection activity.

Example:

vb
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

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

Client with Reconnect

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

Last Updated: 2026-01-10

VB6 and LOGO copyright of Microsoft Corporation