Skip to content

cWebSocketServer Class Reference

📋 Class Overview

cWebSocketServer is a WebSocket server implementation class that provides functionality to listen on ports, manage multiple client connections, and broadcast messages.


📡 Event List

Event NameTrigger TimingParameters
OnStartServer startedPort (Listening port)
OnStopServer stoppedNone
OnClientConnectNew client connectedClientID, RemoteAddress, RemotePort
OnClientDisconnectClient disconnectedClientID, Reason
OnClientTextMessageText message received from clientClientID, Message
OnClientBinaryMessageBinary message received from clientClientID, Data()
OnErrorError occurredDescription

🔧 Property Reference

Port - Listening Port

Type: Long
Read/Write: Read-only

Description: The currently listening port number.

Example:

vb
Debug.Print "Server listening port: " & m_Server.Port

IsListening - Is Listening

Type: Boolean
Read/Write: Read-only

Description: Whether the server is currently listening.

Example:

vb
If m_Server.IsListening Then
    Debug.Print "Server is listening"
End If

ClientCount - Client Connection Count

Type: Long
Read/Write: Read-only

Description: Number of currently connected clients.

Example:

vb
Debug.Print "Current connections: " & m_Server.ClientCount

' Update UI
lblClientCount.Caption = "Connections: " & m_Server.ClientCount

ClientIDs - Client ID Array

Type: Variant (String array)
Read/Write: Read-only

Description: Array of all connected client IDs.

Example:

vb
' Get all client IDs
Dim vIDs() As Variant
vIDs = m_Server.ClientIDs

' Iterate all client IDs
Dim i As Long
For i = LBound(vIDs) To UBound(vIDs)
    Debug.Print "Client: " & vIDs(i)
Next i

🚀 Method Reference

Listen - Start Listening

Syntax:

vb
Public Sub Listen(Optional ByVal Port As Long = 8080)

Parameters:

ParameterTypeDescription
PortLong (Optional)Listening port number, default 8080

Description:

  • If server is already listening, it will stop first then start
  • Triggers OnStart event after starting
  • Automatically initializes client collection

Example:

vb
' Use default port 8080
m_Server.Listen

' Specify port
m_Server.Listen 9000

' Read port from config file
m_Server.Listen CLng(GetConfig("ServerPort"))

Error Handling:

vb
Private Sub cmdStart_Click()
    On Error GoTo EH

    m_Server.Listen CLng(txtPort.Text)
    Debug.Print "Server started"
    Exit Sub

EH:
    Debug.Print "Start failed: " & Err.Description
    MsgBox "Cannot start server: " & Err.Description, vbExclamation
End Sub

StopServer - Stop Server

Syntax:

vb
Public Sub StopServer()

Description:

  • Sends close frames to all clients
  • Closes all client connections
  • Clears client collection
  • Closes listening socket
  • Triggers OnStop event

Example:

vb
' Stop server
m_Server.StopServer
Debug.Print "Server stopped"

' Auto stop on form close
Private Sub Form_Unload(Cancel As Integer)
    m_Server.StopServer
End Sub

SendText - Send Text Message

Syntax:

vb
Public Sub SendText(ByVal ClientID As String, ByVal Message As String)

Parameters:

ParameterTypeDescription
ClientIDStringTarget client ID
MessageStringText message to send

Description: Sends text message to specified client. Message is automatically added WebSocket frame header, server sends without masking.

Example:

vb
' Send welcome message
m_Server.SendText ClientID, "Welcome to WebSocket Server!"

' Echo message
m_Server.SendText ClientID, "Server received: " & Message

' Send JSON data
Dim sJSON As String
sJSON = "{""type"":""notification"", ""message"":""Hello""}"
m_Server.SendText ClientID, sJSON

' Send system message
m_Server.SendText ClientID, "[System] Server will maintain in 5 minutes"

SendBinary - Send Binary Message

Syntax:

vb
Public Sub SendBinary(ByVal ClientID As String, Data() As Byte)

Parameters:

ParameterTypeDescription
ClientIDStringTarget client ID
Data()Byte()Binary data to send

Example:

vb
' Send image data
Dim baImage() As Byte
baImage = LoadImageAsByteArray()
m_Server.SendBinary ClientID, baImage

' Send file data
Dim baFile() As Byte
baFile = LoadFile("document.pdf")
m_Server.SendBinary ClientID, baFile

' Send serialized object
Dim baObj() As Byte
baObj = SerializeObject(myObject)
m_Server.SendBinary ClientID, baObj

BroadcastText - Broadcast Text Message

Syntax:

vb
Public Sub BroadcastText(ByVal Message As String, Optional ByVal ExcludeClientID As String = "")

Parameters:

ParameterTypeDescription
MessageStringText message to broadcast
ExcludeClientIDString (Optional)Client ID to exclude (don't send to this client)

Description: Sends text message to all connected clients. Frame is built once then sent to all clients for better performance.

Example:

vb
' Broadcast to all clients
m_Server.BroadcastText "Welcome to chat room!"

' Broadcast excluding sender
m_Server.BroadcastText Message, SenderClientID

' System announcement
m_Server.BroadcastText "[System] Server will restart in 5 minutes"

' Chat message broadcast
Private Sub m_Server_OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)
    ' Broadcast message to all other clients, excluding sender
    m_Server.BroadcastText ClientID & ": " & Message, ClientID
End Sub

' Scheduled broadcast
Private Sub Timer1_Timer()
    Dim sTime As String
    sTime = Format$(Now, "yyyy-mm-dd hh:nn:ss")
    m_Server.BroadcastText "[Time] " & sTime
End Sub

BroadcastBinary - Broadcast Binary Message

Syntax:

vb
Public Sub BroadcastBinary(Data() As Byte, Optional ByVal ExcludeClientID As String = "")

Parameters:

ParameterTypeDescription
Data()Byte()Binary data to broadcast
ExcludeClientIDString (Optional)Client ID to exclude

Example:

vb
' Broadcast image update
Dim baImage() As Byte
baImage = GetUpdatedImage()
m_Server.BroadcastBinary baImage

' Broadcast config file
Dim baConfig() As Byte
baConfig = SerializeConfig()
m_Server.BroadcastBinary baConfig

' Exclude sender
m_Server.BroadcastBinary baData, SenderClientID

DisconnectClient - Disconnect Client

Syntax:

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

Parameters:

ParameterTypeDescription
ClientIDStringClient ID to disconnect
CodeWsCloseCode (Optional)Close status code, default WS_CLOSE_NORMAL
ReasonString (Optional)Close reason

Example:

vb
' Normal disconnect
m_Server.DisconnectClient ClientID

' Specify close reason
m_Server.DisconnectClient ClientID, WS_CLOSE_GOING_AWAY, "Admin disconnect"

' Violating user disconnect
If IsViolation(ClientID) Then
    m_Server.DisconnectClient ClientID, WS_CLOSE_POLICY_VIOLATION, "Violating chat rules"
End If

' Disconnect all clients during maintenance
Private Sub PrepareForMaintenance()
    Dim vIDs() As Variant
    Dim i As Long
    vIDs = m_Server.ClientIDs
    
    For i = LBound(vIDs) To UBound(vIDs)
        m_Server.DisconnectClient vIDs(i), WS_CLOSE_GOING_AWAY, "Server maintenance"
    Next i
End Sub

📡 Event Details

OnStart - Server Started

Syntax:

vb
Event OnStart(ByVal Port As Long)

Parameters:

ParameterTypeDescription
PortLongListening port number

Example:

vb
Private Sub m_Server_OnStart(ByVal Port As Long)
    Debug.Print "Server started, listening on port: " & Port
    
    ' Update UI
    lblStatus.Caption = "Running"
    lblPort.Caption = Port
    
    ' Log event
    LogEvent "Server started on port " & Port
    
    ' Start scheduled tasks
    Timer1.Enabled = True
End Sub

OnStop - Server Stopped

Syntax:

vb
Event OnStop()

Example:

vb
Private Sub m_Server_OnStop()
    Debug.Print "Server stopped"
    
    ' Update UI
    lblStatus.Caption = "Stopped"
    
    ' Log event
    LogEvent "Server stopped"
    
    ' Stop scheduled tasks
    Timer1.Enabled = False
End Sub

OnClientConnect - Client Connected

Syntax:

vb
Event OnClientConnect(ByVal ClientID As String, ByVal RemoteAddress As String, ByVal RemotePort As Long)

Parameters:

ParameterTypeDescription
ClientIDStringUnique client identifier (format: Client#N)
RemoteAddressStringClient IP address
RemotePortLongClient port

Example:

vb
Private Sub m_Server_OnClientConnect(ByVal ClientID As String, ByVal RemoteAddress As String, ByVal RemotePort As Long)
    Debug.Print "Client connected: " & ClientID & " (" & RemoteAddress & ":" & RemotePort & ")"
    
    ' Add to client list
    lstClients.AddItem ClientID & " - " & RemoteAddress
    
    ' Send welcome message
    m_Server.SendText ClientID, "Welcome to WebSocket Server!"
    
    ' Send current online count
    m_Server.SendText ClientID, "Current online users: " & m_Server.ClientCount
    
    ' Broadcast new user online
    m_Server.BroadcastText "[System] " & ClientID & " is now online", ClientID
    
    ' Log connection
    LogConnection ClientID, RemoteAddress, RemotePort, "Connected"
    
    ' IP whitelist/blacklist check (should be during handshake)
    If IsBlacklisted(RemoteAddress) Then
        m_Server.DisconnectClient ClientID, WS_CLOSE_POLICY_VIOLATION, "IP blocked"
        LogConnection ClientID, RemoteAddress, RemotePort, "Blocked (Blacklist)"
    End If
End Sub

OnClientDisconnect - Client Disconnected

Syntax:

vb
Event OnClientDisconnect(ByVal ClientID As String, ByVal Reason As String)

Parameters:

ParameterTypeDescription
ClientIDStringClient ID
ReasonStringDisconnect reason

Example:

vb
Private Sub m_Server_OnClientDisconnect(ByVal ClientID As String, ByVal Reason As String)
    Debug.Print "Client disconnected: " & ClientID & " - " & Reason
    
    ' Remove from list
    Dim i As Long
    For i = 0 To lstClients.ListCount - 1
        If InStr(lstClients.List(i), ClientID) > 0 Then
            lstClients.RemoveItem i
            Exit For
        End If
    Next
    
    ' Update connection count
    UpdateClientCount
    
    ' Broadcast user offline
    m_Server.BroadcastText "[System] " & ClientID & " is now offline"
    
    ' Log disconnect
    LogDisconnect ClientID, Reason
    
    ' If VIP user, send notification
    If IsVIPClient(ClientID) Then
        NotifyAdmin "VIP user " & ClientID & " disconnected: " & Reason
    End If
End Sub

OnClientTextMessage - Text Message Received from Client

Syntax:

vb
Event OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)

Parameters:

ParameterTypeDescription
ClientIDStringClient ID sending the message
MessageStringMessage content

Example:

vb
Private Sub m_Server_OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)
    Debug.Print "Received message from " & ClientID & ": " & Message
    
    ' Log message
    LogMessage ClientID, Message
    
    ' Handle command
    If Left$(Message, 1) = "/" Then
        ProcessCommand ClientID, Message
        Exit Sub
    End If
    
    ' Echo message
    m_Server.SendText ClientID, "Server received: " & Message
    
    ' Broadcast to other clients (chat mode)
    If m_bChatMode Then
        m_Server.BroadcastText ClientID & ": " & Message, ClientID
    End If
    
    ' Special command: broadcast
    If LCase$(Message) = "broadcast" Then
        m_Server.BroadcastText "This is a broadcast message from client " & ClientID, ClientID
    End If
End Sub

Private Sub ProcessCommand(ByVal ClientID As String, ByVal Command As String)
    Dim sCmd As String
    Dim sArgs() As String
    Dim sArgsList As String
    
    ' Parse command
    sCmd = LCase$(Mid$(Command, 2))
    sArgsList = Mid$(Command, 2)
    sArgs = Split(sArgsList, " ")
    
    Select Case sCmd
        Case "users"
            ' List all users
            Dim sUserList As String
            sUserList = "Online users: "
            Dim vIDs() As Variant
            vIDs = m_Server.ClientIDs
            Dim i As Long
            For i = LBound(vIDs) To UBound(vIDs)
                sUserList = sUserList & vIDs(i) & " "
            Next i
            m_Server.SendText ClientID, sUserList
            
        Case "time"
            ' Send server time
            m_Server.SendText ClientID, "Server time: " & Now
            
        Case "ping"
            ' Reply Pong
            m_Server.SendText ClientID, "pong"
            
        Case Else
            m_Server.SendText ClientID, "Unknown command: " & sCmd
    End Select
End Sub

OnClientBinaryMessage - Binary Message Received from Client

Syntax:

vb
Event OnClientBinaryMessage(ByVal ClientID As String, Data() As Byte)

Parameters:

ParameterTypeDescription
ClientIDStringClient ID sending the message
Data()Byte()Binary data

Example:

vb
Private Sub m_Server_OnClientBinaryMessage(ByVal ClientID As String, Data() As Byte)
    On Error Resume Next
    
    Debug.Print "Received binary message from " & ClientID & ": " & (UBound(Data) + 1) & " bytes"
    
    ' Log binary message
    LogBinaryMessage ClientID, UBound(Data) + 1
    
    ' 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 ' Image upload
                SaveUploadedPicture ClientID, ExtractData(Data, 4)
                m_Server.SendText ClientID, "Image saved"
                
            Case 2 ' File upload
                SaveUploadedFile ClientID, ExtractData(Data, 4)
                m_Server.SendText ClientID, "File saved"
                
            Case 3 ' Custom data
                ProcessCustomData ClientID, ExtractData(Data, 4)
                
            Case Else
                Debug.Print "Unknown data type: " & lType
        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_Server_OnError(ByVal Description As String)
    Debug.Print "Server error: " & Description
    
    ' Log error
    LogError Description
    
    ' Show error alert
    If m_bShowErrors Then
        MsgBox "Server error: " & Description, vbExclamation
    End If
    
    ' Stop server on critical error
    If InStr(Description, "critical") > 0 Then
        m_Server.StopServer
    End If
End Sub

📝 Complete Example

Basic Chat Server

vb
Private WithEvents m_Server As cWebSocketServer
Private m_bChatMode As Boolean

Private Sub Form_Load()
    Set m_Server = New cWebSocketServer
    m_bChatMode = True
End Sub

Private Sub cmdStart_Click()
    m_Server.Listen CLng(txtPort.Text)
End Sub

Private Sub cmdStop_Click()
    m_Server.StopServer
End Sub

Private Sub m_Server_OnStart(ByVal Port As Long)
    Debug.Print "Server started: " & Port
    lblStatus.Caption = "Running"
End Sub

Private Sub m_Server_OnClientConnect(ByVal ClientID As String, ByVal RemoteAddress As String, ByVal RemotePort As Long)
    Debug.Print "Client connected: " & ClientID
    lstClients.AddItem ClientID
    m_Server.SendText ClientID, "Welcome to chat room!"
    m_Server.BroadcastText ClientID & " joined chat room", ClientID
End Sub

Private Sub m_Server_OnClientDisconnect(ByVal ClientID As String, ByVal Reason As String)
    Debug.Print "Client disconnected: " & ClientID
    Dim i As Long
    For i = 0 To lstClients.ListCount - 1
        If lstClients.List(i) = ClientID Then
            lstClients.RemoveItem i
            Exit For
        End If
    Next
    m_Server.BroadcastText ClientID & " left chat room"
End Sub

Private Sub m_Server_OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)
    Debug.Print ClientID & ": " & Message
    txtLog.Text = txtLog.Text & ClientID & ": " & Message & vbCrLf
    
    ' Broadcast to all other clients
    m_Server.BroadcastText ClientID & ": " & Message, ClientID
End Sub

Private Sub m_Server_OnError(ByVal Description As String)
    Debug.Print "Error: " & Description
End Sub

Private Sub Form_Unload(Cancel As Integer)
    m_Server.StopServer
End Sub

Last Updated: 2026-01-10

VB6 and LOGO copyright of Microsoft Corporation