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 Name | Trigger Timing | Parameters |
|---|---|---|
OnStart | Server started | Port (Listening port) |
OnStop | Server stopped | None |
OnClientConnect | New client connected | ClientID, RemoteAddress, RemotePort |
OnClientDisconnect | Client disconnected | ClientID, Reason |
OnClientTextMessage | Text message received from client | ClientID, Message |
OnClientBinaryMessage | Binary message received from client | ClientID, Data() |
OnError | Error occurred | Description |
🔧 Property Reference
Port - Listening Port
Type: Long
Read/Write: Read-only
Description: The currently listening port number.
Example:
Debug.Print "Server listening port: " & m_Server.PortIsListening - Is Listening
Type: Boolean
Read/Write: Read-only
Description: Whether the server is currently listening.
Example:
If m_Server.IsListening Then
Debug.Print "Server is listening"
End IfClientCount - Client Connection Count
Type: Long
Read/Write: Read-only
Description: Number of currently connected clients.
Example:
Debug.Print "Current connections: " & m_Server.ClientCount
' Update UI
lblClientCount.Caption = "Connections: " & m_Server.ClientCountClientIDs - Client ID Array
Type: Variant (String array)
Read/Write: Read-only
Description: Array of all connected client IDs.
Example:
' 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:
Public Sub Listen(Optional ByVal Port As Long = 8080)Parameters:
| Parameter | Type | Description |
|---|---|---|
Port | Long (Optional) | Listening port number, default 8080 |
Description:
- If server is already listening, it will stop first then start
- Triggers
OnStartevent after starting - Automatically initializes client collection
Example:
' 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:
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 SubStopServer - Stop Server
Syntax:
Public Sub StopServer()Description:
- Sends close frames to all clients
- Closes all client connections
- Clears client collection
- Closes listening socket
- Triggers
OnStopevent
Example:
' 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 SubSendText - Send Text Message
Syntax:
Public Sub SendText(ByVal ClientID As String, ByVal Message As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Target client ID |
Message | String | Text message to send |
Description: Sends text message to specified client. Message is automatically added WebSocket frame header, server sends without masking.
Example:
' 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:
Public Sub SendBinary(ByVal ClientID As String, Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Target client ID |
Data() | Byte() | Binary data to send |
Example:
' 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, baObjBroadcastText - Broadcast Text Message
Syntax:
Public Sub BroadcastText(ByVal Message As String, Optional ByVal ExcludeClientID As String = "")Parameters:
| Parameter | Type | Description |
|---|---|---|
Message | String | Text message to broadcast |
ExcludeClientID | String (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:
' 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 SubBroadcastBinary - Broadcast Binary Message
Syntax:
Public Sub BroadcastBinary(Data() As Byte, Optional ByVal ExcludeClientID As String = "")Parameters:
| Parameter | Type | Description |
|---|---|---|
Data() | Byte() | Binary data to broadcast |
ExcludeClientID | String (Optional) | Client ID to exclude |
Example:
' 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, SenderClientIDDisconnectClient - Disconnect Client
Syntax:
Public Sub DisconnectClient(ByVal ClientID As String, _
Optional ByVal Code As WsCloseCode = WS_CLOSE_NORMAL, _
Optional ByVal Reason As String = "")Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Client ID to disconnect |
Code | WsCloseCode (Optional) | Close status code, default WS_CLOSE_NORMAL |
Reason | String (Optional) | Close reason |
Example:
' 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:
Event OnStart(ByVal Port As Long)Parameters:
| Parameter | Type | Description |
|---|---|---|
Port | Long | Listening port number |
Example:
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 SubOnStop - Server Stopped
Syntax:
Event OnStop()Example:
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 SubOnClientConnect - Client Connected
Syntax:
Event OnClientConnect(ByVal ClientID As String, ByVal RemoteAddress As String, ByVal RemotePort As Long)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Unique client identifier (format: Client#N) |
RemoteAddress | String | Client IP address |
RemotePort | Long | Client port |
Example:
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 SubOnClientDisconnect - Client Disconnected
Syntax:
Event OnClientDisconnect(ByVal ClientID As String, ByVal Reason As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Client ID |
Reason | String | Disconnect reason |
Example:
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 SubOnClientTextMessage - Text Message Received from Client
Syntax:
Event OnClientTextMessage(ByVal ClientID As String, ByVal Message As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Client ID sending the message |
Message | String | Message content |
Example:
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 SubOnClientBinaryMessage - Binary Message Received from Client
Syntax:
Event OnClientBinaryMessage(ByVal ClientID As String, Data() As Byte)Parameters:
| Parameter | Type | Description |
|---|---|---|
ClientID | String | Client ID sending the message |
Data() | Byte() | Binary data |
Example:
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 SubOnError - Error Occurred
Syntax:
Event OnError(ByVal Description As String)Parameters:
| Parameter | Type | Description |
|---|---|---|
Description | String | Error description |
Example:
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
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 SubLast Updated: 2026-01-10