Skip to content

cWinsock Events Reference

📋 Event List

Event NameDescriptionTrigger Timing
ConnectClient connected successfullyTCP client successfully connects to server
CloseEventConnection closedTCP connection closed
ConnectionRequestNew connection requestServer receives new connection request
DataArrivalData arrivedNew data received
SendProgressSend progressTriggered during data sending
SendCompleteSend completedData sending completed
ErrorError occurredSocket error occurred

🔗 Connect Event

Description

Triggered when a TCP client successfully connects to the server.

Syntax

vb
Private Sub object_Connect(Client As cWinsock)

Parameters

ParameterTypeDescription
ClientcWinsockClient object that triggered the event (i.e., Me)

Usage Example

vb
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

vb
Private Sub object_CloseEvent(Client As cWinsock)

Parameters

ParameterTypeDescription
ClientcWinsockClient object that triggered the event

Important Notes

For clients accepted by the server, when CloseEvent is triggered, it automatically:

  1. Removes that client from the server's Clients collection
  2. Cleans up related resources

Usage Example

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

Server-side example:

vb
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

vb
Private Sub object_ConnectionRequest(Client As cWinsock, ByRef DisConnect As Boolean)

Parameters

ParameterTypeDescription
ClientcWinsockNew client object
DisConnectBooleanSet to True to reject connection and clean up resources

Connection Interception Mechanism

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

Advanced Example: Dynamic Whitelist

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

Triggering in TCP vs UDP

ProtocolTrigger Timing
TCPReceived new connection request (accept system call)
UDPFirst 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

vb
Private Sub object_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)

Parameters

ParameterTypeDescription
ClientcWinsockClient object receiving data
bytesTotalLongNumber of bytes of data available

Basic Usage

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

Reading Byte Array

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

Partial Data Reading

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

Specified Encoding Reading

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

Event Proxy Mechanism

Important: For client objects accepted by the server, their DataArrival event is triggered through the parent server object.

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

vb
Private Sub object_SendProgress(Client As cWinsock, ByVal bytesSent As Long, ByVal bytesRemaining As Long)

Parameters

ParameterTypeDescription
ClientcWinsockClient object sending data
bytesSentLongNumber of bytes sent
bytesRemainingLongNumber of bytes remaining to send

Usage Example

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

Practical Application: File Transfer Progress

vb
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

vb
Private Sub object_SendComplete(Client As cWinsock)

Parameters

ParameterTypeDescription
ClientcWinsockClient object that finished sending

Usage Example

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

Practical Application: Command Queue

vb
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

vb
Private Sub object_Error(Client As cWinsock, ByVal Number As Long, Description As String, ByVal Scode As Long)

Parameters

ParameterTypeDescription
ClientcWinsockClient object where error occurred
NumberLongError code
DescriptionStringError description
ScodeLongSCODE (usually same as Number)

Common Error Codes

Error CodeDescription
10053Connection forcibly closed by remote host
10054Remote host closed the connection
10060Connection timeout
10061Connection refused
10065Target host unreachable
10048Address already in use

Usage Example

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

Error Recovery

vb
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

  1. Event Processing Time

    • Avoid executing time-consuming operations in event handlers
    • Use DoEvents to release control
    • Or put time-consuming operations in queue for asynchronous processing
  2. Object Lifecycle

    • Don't Set Client = Nothing in event handlers
    • Client objects managed by server, automatically cleaned up
  3. Thread Safety

    • Events triggered in main thread, can access UI directly
    • But avoid re-entrancy issues
  4. Error Handling

    • Always use On Error GoTo to handle errors in events
    • Prevent one client's error from affecting other clients

Last Updated: 2026-01-09

VB6 and LOGO copyright of Microsoft Corporation