cWinsock Events Reference
📋 Event List
| Event Name | Description | Trigger Timing |
|---|---|---|
Connect | Client connected successfully | TCP client successfully connects to server |
CloseEvent | Connection closed | TCP connection closed |
ConnectionRequest | New connection request | Server receives new connection request |
DataArrival | Data arrived | New data received |
SendProgress | Send progress | Triggered during data sending |
SendComplete | Send completed | Data sending completed |
Error | Error occurred | Socket error occurred |
🔗 Connect Event
Description
Triggered when a TCP client successfully connects to the server.
Syntax
Private Sub object_Connect(Client As cWinsock)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object that triggered the event (i.e., Me) |
Usage Example
Private WithEvents m_oClient As cWinsock
Private Sub m_oClient_Connect(Client As cWinsock)
Debug.Print "Connected to server"
Debug.Print "Remote address: " & Client.RemoteHostIP
Debug.Print "Remote port: " & Client.RemotePort
' Send login request after connection
Client.SendData "LOGIN|user|password"
End Sub🚪 CloseEvent Event
Description
Triggered when a TCP connection is closed.
Syntax
Private Sub object_CloseEvent(Client As cWinsock)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object that triggered the event |
Important Notes
For clients accepted by the server, when CloseEvent is triggered, it automatically:
- Removes that client from the server's
Clientscollection - Cleans up related resources
Usage Example
Private Sub m_oClient_CloseEvent(Client As cWinsock)
Debug.Print "Connection closed"
' Can try to reconnect here
If m_bAutoReconnect Then
Debug.Print "Attempting to reconnect in 3 seconds..."
tmrReconnect.Enabled = True
End If
End SubServer-side example:
Private Sub m_oServer_CloseEvent(Client As cWinsock)
Debug.Print "Client " & Client.Tag & " disconnected"
' Update UI
Dim i As Long
For i = 0 To lstClients.ListCount - 1
If lstClients.List(i) = Client.Tag Then
lstClients.RemoveItem i
Exit For
End If
Next
' Update statistics
UpdateClientCount
End Sub🔔 ConnectionRequest Event
Description
Triggered when the server receives a new connection request. Supports connection interception via the DisConnect parameter.
Syntax
Private Sub object_ConnectionRequest(Client As cWinsock, ByRef DisConnect As Boolean)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | New client object |
DisConnect | Boolean | Set to True to reject connection and clean up resources |
Connection Interception Mechanism
Private Sub m_oServer_ConnectionRequest(Client As cWinsock, ByRef DisConnect As Boolean)
' Accept connection by default (DisConnect = False)
' 1. IP blacklist check
If IsInBlacklist(Client.RemoteHostIP) Then
Debug.Print "Reject blacklist IP: " & Client.RemoteHostIP
DisConnect = True
Exit Sub
End If
' 2. Port range restriction
If Client.RemotePort < 1024 Then
Debug.Print "Reject privileged port: " & Client.RemotePort
DisConnect = True
Exit Sub
End If
' 3. Whitelist mode
If m_bWhitelistMode Then
If Not IsInWhitelist(Client.RemoteHostIP) Then
Debug.Print "IP not in whitelist: " & Client.RemoteHostIP
DisConnect = True
Exit Sub
End If
End If
' 4. Connection count limit
If m_oServer.ClientCount >= m_lMaxClients Then
Debug.Print "Maximum connection limit reached"
DisConnect = True
Exit Sub
End If
' Accept connection
Debug.Print "Accept new client: " & Client.RemoteHostIP & ":" & Client.RemotePort
DisConnect = False
End SubAdvanced Example: Dynamic Whitelist
Private Sub m_oServer_ConnectionRequest(Client As cWinsock, ByRef DisConnect As Boolean)
' Load whitelist from database or config file
Dim sWhitelist() As String
sWhitelist = LoadWhitelistFromDatabase()
Dim bAllowed As Boolean
bAllowed = False
Dim i As Long
For i = LBound(sWhitelist) To UBound(sWhitelist)
If sWhitelist(i) = Client.RemoteHostIP Then
bAllowed = True
Exit For
End If
Next
If Not bAllowed Then
Debug.Print "Reject unauthorized IP: " & Client.RemoteHostIP
DisConnect = True
End If
End SubTriggering in TCP vs UDP
| Protocol | Trigger Timing |
|---|---|
| TCP | Received new connection request (accept system call) |
| UDP | First time receiving packet from new address:port |
📨 DataArrival Event
Description
Triggered when new data is received. This is one of the most commonly used events.
Syntax
Private Sub object_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object receiving data |
bytesTotal | Long | Number of bytes of data available |
Basic Usage
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
Dim sData As String
' Read string data
Client.GetData sData
Debug.Print "Received " & bytesTotal & " bytes: " & sData
' Process data...
ProcessData Client, sData
End SubReading Byte Array
Private Sub m_oClient_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
Dim baData() As Byte
' Read byte array
Client.GetData baData
Debug.Print "Received " & bytesTotal & " bytes of data"
' Process binary data...
ProcessBinaryData baData
End SubPartial Data Reading
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
Dim sHeader As String
Dim sBody As String
' Read first 10 bytes as header
Client.GetData sHeader, vbString, 10
Debug.Print "Header: " & sHeader
' Read remaining data (still in buffer)
Client.GetData sBody
Debug.Print "Body: " & sBody
End SubSpecified Encoding Reading
Private Sub m_oClient_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
Dim sData As String
' Read using UTF-8 encoding
Client.GetData sData, vbString, -1, ucsScpUtf8
Debug.Print "UTF-8 data: " & sData
End SubEvent Proxy Mechanism
Important: For client objects accepted by the server, their DataArrival event is triggered through the parent server object.
' Only need to subscribe to server events to handle all client data
Private WithEvents m_oServer As cWinsock
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
' Client parameter is the specific client object
Debug.Print "Data from " & Client.Tag
Dim sData As String
Client.GetData sData
' Can reply directly to that client
Client.SendData "Echo: " & sData
End Sub📊 SendProgress Event
Description
Triggered periodically during data sending, used to display send progress.
Syntax
Private Sub object_SendProgress(Client As cWinsock, ByVal bytesSent As Long, ByVal bytesRemaining As Long)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object sending data |
bytesSent | Long | Number of bytes sent |
bytesRemaining | Long | Number of bytes remaining to send |
Usage Example
Private Sub m_oClient_SendProgress(Client As cWinsock, ByVal bytesSent As Long, ByVal bytesRemaining As Long)
Dim lTotal As Long
lTotal = bytesSent + bytesRemaining
Dim dPercent As Double
dPercent = (bytesSent / lTotal) * 100
Debug.Print "Send progress: " & Format$(dPercent, "0.00") & "% (" & bytesSent & "/" & lTotal & ")"
' Update progress bar
If Not prgProgress Is Nothing Then
prgProgress.Value = CInt(dPercent)
End If
End SubPractical Application: File Transfer Progress
Private Sub m_oClient_SendProgress(Client As cWinsock, ByVal bytesSent As Long, ByVal bytesRemaining As Long)
Static lStartTime As Long
Static lLastUpdate As Long
If lStartTime = 0 Then lStartTime = Timer
If lLastUpdate = 0 Then lLastUpdate = lStartTime
' Update UI every 0.5 seconds
If Timer - lLastUpdate >= 0.5 Then
Dim lTotal As Long
lTotal = bytesSent + bytesRemaining
Dim dElapsed As Double
dElapsed = Timer - lStartTime
Dim dSpeed As Double
dSpeed = bytesSent / dElapsed ' bytes/second
' Update UI
lblStatus.Caption = "Sending: " & FormatSize(bytesSent) & " / " & FormatSize(lTotal)
lblSpeed.Caption = "Speed: " & FormatSize(dSpeed) & "/s"
lLastUpdate = Timer
End If
End Sub✅ SendComplete Event
Description
Triggered when data sending is completed.
Syntax
Private Sub object_SendComplete(Client As cWinsock)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object that finished sending |
Usage Example
Private Sub m_oClient_SendComplete(Client As cWinsock)
Debug.Print "Data sending completed"
' Reset send status
m_bSending = False
' Update UI
cmdSend.Enabled = True
lblStatus.Caption = "Ready"
End SubPractical Application: Command Queue
Private m_lCommandQueue() As String
Private m_lQueueIndex As Long
Private Sub SendNextCommand()
If m_lQueueIndex <= UBound(m_lCommandQueue) Then
m_oClient.SendData m_lCommandQueue(m_lQueueIndex)
m_lQueueIndex = m_lQueueIndex + 1
End If
End Sub
Private Sub m_oClient_SendComplete(Client As cWinsock)
Debug.Print "Command send completed, sending next..."
SendNextCommand
End Sub❌ Error Event
Description
Triggered when a Socket error occurs.
Syntax
Private Sub object_Error(Client As cWinsock, ByVal Number As Long, Description As String, ByVal Scode As Long)Parameters
| Parameter | Type | Description |
|---|---|---|
Client | cWinsock | Client object where error occurred |
Number | Long | Error code |
Description | String | Error description |
Scode | Long | SCODE (usually same as Number) |
Common Error Codes
| Error Code | Description |
|---|---|
| 10053 | Connection forcibly closed by remote host |
| 10054 | Remote host closed the connection |
| 10060 | Connection timeout |
| 10061 | Connection refused |
| 10065 | Target host unreachable |
| 10048 | Address already in use |
Usage Example
Private Sub m_oClient_Error(Client As cWinsock, ByVal Number As Long, Description As String, ByVal Scode As Long)
Debug.Print "Socket error [" & Number & "]: " & Description
Select Case Number
Case 10053, 10054
' Connection closed
Debug.Print "Remote host disconnected"
Case 10060
' Connection timeout
Debug.Print "Connection timeout, please check network"
Case 10061
' Connection refused
Debug.Print "Server refused connection, please check port and firewall"
Case Else
' Other errors
Debug.Print "Unknown error: " & Description
End Select
End SubError Recovery
Private Sub m_oServer_Error(Client As cWinsock, ByVal Number As Long, Description As String, ByVal Scode As Long)
Debug.Print "Server error [" & Number & "]: " & Description
' Remove error client
If Not Client Is Nothing Then
m_oServer.RemoveClient Client
End If
' If serious error, restart server
If Number >= 10000 Then
Debug.Print "Serious error, restarting server..."
m_oServer.Close_
m_oServer.Listen m_lServerPort
End If
End Sub🎯 Event Trigger Order
TCP Client Connection Flow
1. Connect() call
2. Internal hostname resolution
3. Connect event triggered
4. Can start sending data
5. SendProgress event (multiple times)
6. SendComplete event triggered
7. DataArrival event (receive data)
8. CloseEvent event (connection closed)TCP Server Accept Connection Flow
1. Listen() call
2. Receive new connection request
3. ConnectionRequest event triggered (can intercept)
4. If accepted, create client object
5. Client DataArrival event (triggered through server)
6. Client CloseEvent event (triggered on disconnect)UDP Communication Flow
1. Bind() call (UDP server)
2. Receive packet
3. First time receiving from that address:port → ConnectionRequest event
4. DataArrival event triggered
5. Can reply via SendData📌 Notes
Event Processing Time
- Avoid executing time-consuming operations in event handlers
- Use
DoEventsto release control - Or put time-consuming operations in queue for asynchronous processing
Object Lifecycle
- Don't
Set Client = Nothingin event handlers - Client objects managed by server, automatically cleaned up
- Don't
Thread Safety
- Events triggered in main thread, can access UI directly
- But avoid re-entrancy issues
Error Handling
- Always use
On Error GoToto handle errors in events - Prevent one client's error from affecting other clients
- Always use
Last Updated: 2026-01-09