Skip to content

cWinsock Development Plan

📋 Project Development Progress Tracking Document

📖 Table of Contents


✅ Completed Features

Core Features

1. Basic Network Communication

  • [x] TCP client/server communication
  • [x] UDP client/server communication
  • [x] Async socket encapsulation (based on VbAsyncSocket)
  • [x] Connection state management
  • [x] Exception handling mechanism

2. Event-Driven Model

  • [x] Connect event (connection successful)
  • [x] CloseEvent event (connection closed)
  • [x] ConnectionRequest event (new connection request)
  • [x] DataArrival event (data arrived)
  • [x] SendProgress event (send progress)
  • [x] SendComplete event (send completed)
  • [x] Error event (error handling)

3. Object Model Design

  • [x] Pure class implementation, no controls required
  • [x] Direct object reference passing (no index lookup needed)
  • [x] Automatic client collection management (Clients collection)
  • [x] Server-client parent-child relationship maintenance
  • [x] Event proxy mechanism (server unified handling of client events)

4. TCP Client Event Proxy

  • [x] Automatic triggering of client events through parent server
  • [x] Unified data arrival handling
  • [x] Unified connection disconnection handling
  • [x] Unified error handling

5. UDP Virtual Client Management

  • [x] Create virtual client objects for each remote address:port
  • [x] Simulate TCP connection behavior
  • [x] Support ConnectionRequest event
  • [x] Automatically maintain virtual client collection

6. Connection Request Interception

  • [x] DisConnect parameter in ConnectionRequest event
  • [x] Blacklist mechanism
  • [x] Whitelist mechanism
  • [x] Port range restriction
  • [x] Automatic disconnect and resource cleanup

7. Text Encoding Support

  • [x] ScpAcp (system default code page, GBK)
  • [x] ScpUtf8 (UTF-8 encoding)
  • [x] ScpUnicode (Unicode wide characters)
  • [x] Flexible string/byte array conversion

8. Data Buffer Management

  • [x] TCP receive buffer (m_baRecvBuffer)
  • [x] UDP virtual client buffer (UserData)
  • [x] Partial read support
  • [x] Automatic buffer of remaining data

9. Remote Address Resolution

  • [x] Automatic domain name resolution
  • [x] Smart selection of IP and domain name
  • [x] RemoteHost/RemoteHostIP/RemotePort properties

10. Application Scenarios

  • [x] TCP server mode
  • [x] TCP client mode
  • [x] UDP server mode
  • [x] UDP client mode
  • [x] Bidirectional communication
  • [x] Broadcast/multicast basic support

🚧 Features Under Development

1. Data Packet Protocol (High Priority)

Feature Description: Solve TCP packet fragmentation and sticky packet issues, providing built-in and custom packet protocol support.

Implementation Details:

1.1 Built-in Protocols

Character Delimiter Protocol
  • Default delimiter: \0 (VbNullChar)
  • Custom delimiter: User can specify any character or string as delimiter
  • Common delimiters:
    • \r\n - Carriage return + line feed (HTTP, SMTP and other text protocols)
    • \n - Line feed
    • \0 - Null character (C string style)
    • | - Vertical bar (custom protocol)
    • Any other character/string
  • Applicable scenarios: Text protocols, custom message formats
Fixed Length Protocol
  • Fixed-length message blocks
  • Applicable to protocols with known lengths
  • Split data by fixed length
Length Header Protocol
  • Message header contains data length information
  • Support different length header formats (2-byte/4-byte integer)
  • Automatically parse complete messages

1.2 Custom Protocol

  • User provides callback function
  • Support complex business logic
  • Flexible packet/unpacket rules

1.3 Protocol Class Design

Unified Interface Design: All protocol classes provide two interface functions: Encode (packet) and Decode (unpacket), and the protocol class internally caches fragmented data.

vb
' Protocol type enumeration
Public Enum PacketProtocol
    ppNone = 0                ' No processing (default)
    ppDelimiter = 1           ' Character delimiter protocol
    ppFixedLength = 2         ' Fixed length protocol
    ppLengthHeader = 3        ' Length header protocol
    ppCustom = 4              ' Custom protocol
End Enum

' Protocol class unified interface
' Encode: called before sending data, used to add protocol markers (packet)
Public Function Encode(ByRef baData() As Byte) As Byte()
    ' Parameter: original data
    ' Return value: complete data with protocol markers added
End Function

' Decode: called after receiving data, used to parse complete messages (unpacket)
Public Function Decode(ByRef baData() As Byte) As Variant
    ' Parameter: currently received data
    ' Return value:
    '   - If data is incomplete, return Empty (protocol class internally caches data)
    '   - If data is complete, return complete message data (byte array)
    '   - If multiple complete messages, return byte array collection
End Function

Internal Responsibilities of Protocol Class:

  • Encode (packet): Add protocol markers at the end or beginning of data
    • Character delimiter protocol: append delimiter at the end of data
    • Fixed length protocol: pad or truncate to fixed length
    • Length header protocol: add length header at the beginning of data
  • Decode (unpacket):
    • Cache fragmented data (class internally maintains receive buffer)
    • Determine if data is complete
    • When data is complete, return complete message and clear internal buffer
    • Automatically handle packet fragmentation and sticky packets

Independent Protocol Instance per Client:

  • In multi-client scenarios, each cWinsock client object holds an independent protocol class instance
  • Internal buffers of protocol classes are isolated from each other without interference
  • Support different clients using different protocol types and parameters

1.4 API Design

vb
' Protocol configuration in cWinsock class
' =============================================

' Set packet protocol type
Public Property Let PacketProtocol(ByVal eProtocol As PacketProtocol)
Public Property Get PacketProtocol() As PacketProtocol

' Character delimiter protocol parameters
Public Property Let Delimiter(ByVal sDelimiter As String)
Public Property Get Delimiter() As String

' Fixed length protocol parameters
Public Property Let FixedLength(ByVal lLength As Long)
Public Property Get FixedLength() As Long

' Length header protocol parameters
Public Property Let HeaderBytes(ByVal nBytes As Integer)  ' 2 or 4
Public Property Get HeaderBytes() As Integer
Public Property Let HeaderEndian(ByVal eEndian As EndianEnum)
Public Property Get HeaderEndian() As EndianEnum

' Custom protocol handler object
Public Property Let CustomPacketHandler(ByVal oHandler As Object)
Public Property Get CustomPacketHandler() As Object

' SendData automatic packet (automatically call protocol Encode method when sending)
Public Sub SendData(Data As Variant, Optional ByVal CodePage As ScpEnum = ScpAcp)

' GetData automatic unpacket (processed through protocol class Decode method when receiving)
Public Sub GetData(Data As Variant, Optional ByVal Type_ As VbVarType, Optional ByVal MaxLen As Long, Optional ByVal CodePage As ScpEnum = ScpAcp)

1.5 Architecture Design

cWinsock Class Internal Structure:

vb
' =============================================
' cWinsock class definition
' =============================================
Public Class cWinsock
    ' Protocol configuration properties
    Private m_ePacketProtocol As PacketProtocol
    Private m_oPacketHandler As Object
    Private m_sDelimiter As String
    Private m_lFixedLength As Long
    Private m_nHeaderBytes As Integer
    
    ' Protocol class instance (independently held by each client object)
    Private m_oPacketProtocol As IPacketProtocol
    
    ' Internal send buffer
    Private m_baSendBuffer() As Byte
    
    ' Internal receive buffer
    Private m_baRecvBuffer() As Byte
    
    ' ... other members ...
End Class

Mechanism of Independent Protocol Instance per Client:

vb
' =============================================
' Protocol instance creation and management
' =============================================

' When setting protocol type, create independent protocol instance for current client object
Public Property Let PacketProtocol(ByVal eProtocol As PacketProtocol)
    m_ePacketProtocol = eProtocol
    
    ' Create independent protocol instance for current cWinsock object
    Set m_oPacketProtocol = CreateProtocolInstance(eProtocol)
End Property

' Private method to create protocol instance for current client
Private Function CreateProtocolInstance(ByVal eProtocol As PacketProtocol) As IPacketProtocol
    Dim oProtocol As IPacketProtocol
    
    Select Case eProtocol
        Case ppDelimiter
            ' Create character delimiter protocol instance (independent per client)
            Set oProtocol = New DelimiterProtocol(IIf(LenB(m_sDelimiter) = 0, vbCrLf, m_sDelimiter))
            
        Case ppFixedLength
            ' Create fixed length protocol instance (independent per client)
            Set oProtocol = New FixedLengthProtocol(m_lFixedLength)
            
        Case ppLengthHeader
            ' Create length header protocol instance (independent per client)
            Set oProtocol = New LengthHeaderProtocol(m_nHeaderBytes)
            
        Case ppCustom
            ' Use custom protocol handler
            Set oProtocol = m_oPacketHandler
            
        Case Else
            Set oProtocol = Nothing
    End Select
    
    Set CreateProtocolInstance = oProtocol
End Function

' When server accepts new connection, new client object automatically inherits server protocol configuration
' and creates its own independent protocol instance
Private Sub OnAcceptClient(ByRef oNewClient As cWinsock)
    ' New client inherits server protocol configuration
    oNewClient.PacketProtocol = Me.PacketProtocol
    oNewClient.Delimiter = Me.Delimiter
    oNewClient.FixedLength = Me.FixedLength
    oNewClient.HeaderBytes = Me.HeaderBytes
    
    ' New client creates its own independent protocol instance (buffer isolation)
    ' oNewClient internally calls CreateProtocolInstance to create new instance
End Sub

' When client closes, clean up its own protocol instance
Private Sub OnClose()
    If Not m_oPacketProtocol Is Nothing Then
        m_oPacketProtocol.Clear  ' Clear protocol internal buffer
        Set m_oPacketProtocol = Nothing
    End If
End Sub

Instance Relationship in Multi-Client Concurrent Scenarios:

Server cWinsock object
├── Protocol configuration properties
│   ├── PacketProtocol = ppDelimiter
│   └── Delimiter = vbCrLf

└── Clients collection
    ├── Client 1 (cWinsock)
    │   ├── Protocol instance 1 (DelimiterProtocol)
    │   │   └── Receive buffer 1 (independent)
    │   └── Socket connection 1

    ├── Client 2 (cWinsock)
    │   ├── Protocol instance 2 (DelimiterProtocol)
    │   │   └── Receive buffer 2 (independent)
    │   └── Socket connection 2

    └── Client 3 (cWinsock)
        ├── Protocol instance 3 (DelimiterProtocol)
        │   └── Receive buffer 3 (independent)
        └── Socket connection 3

Core Advantages:

  • State isolation: Each client's protocol buffer is completely independent without interference
  • Protocol flexibility: Different clients can use different protocol types and parameters
  • Thread safety: In VB6 single-threaded environment, independent state of each object is naturally safe
  • Memory management: Automatically clean up protocol instances and buffers when client disconnects
  • Configuration inheritance: New clients automatically inherit server protocol configuration while creating independent instances

1.6 Implementation Details

Data Flow:

  1. Send flow (SendData):

    • Convert data to byte array
    • Call Encode method of current client object's protocol instance for packet
    • Character delimiter protocol: append delimiter at end of data
    • Fixed length protocol: pad or truncate to fixed length
    • Length header protocol: add length header at beginning of data
    • Custom protocol: call custom handler's Encode method
    • Send complete data after packet
  2. Receive flow (DataArrival):

    • Get original byte data
    • Call Decode method of current client object's protocol instance for unpacket
    • Protocol instance internally merges new data into its own receive buffer
    • Determine if data is complete
    • Data complete: return complete message (with protocol markers removed), trigger event
    • Data incomplete: return Empty, protocol instance internally caches data
    • Continue processing when next data arrives
  3. Buffer management:

    • Each client's protocol instance independently maintains receive buffer
    • Automatically clear its own buffer after data is complete
    • Support continuous reception of multiple messages
    • Clean up its own protocol state when client closes
  4. Multi-client concurrent processing:

    Timeline example:
    
    T1: Client 1 receives "Hel"
        → Call client 1's protocol instance 1.Decode("Hel")
        → Protocol instance 1 buffer: ["Hel"]
        → Return Empty (incomplete)
    
    T2: Client 2 receives "Hi\0"
        → Call client 2's protocol instance 2.Decode("Hi\0")
        → Protocol instance 2 buffer: ["Hi\0"]
        → Parse complete message "Hi"
        → Clear protocol instance 2 buffer
        → Trigger client 2's DataArrival event
    
    T3: Client 1 receives "lo\0"
        → Call client 1's protocol instance 1.Decode("lo\0")
        → Protocol instance 1 buffer: ["Hel"] + ["lo\0"] = ["Hello\0"]
        → Parse complete message "Hello"
        → Clear protocol instance 1 buffer
        → Trigger client 1's DataArrival event
    
    T4: Client 3 receives "Test\0"
        → Call client 3's protocol instance 3.Decode("Test\0")
        → Protocol instance 3 buffer: ["Test\0"]
        → Parse complete message "Test"
        → Clear protocol instance 3 buffer
        → Trigger client 3's DataArrival event
    • Each client object holds independent protocol instance
    • Each protocol instance maintains independent internal buffer
    • Protocol instances do not interfere with each other, independently processing their respective data

1.6 Usage Examples

Example 1: Basic usage (character delimiter protocol)

vb
' Server configuration
Private Sub Form_Load()
    Set m_oServer = New cWinsock
    m_oServer.PacketProtocol = ppDelimiter
    m_oServer.Delimiter = vbNullChar  ' Use null character delimiter
    m_oServer.Listen 8080
End Sub

' Client send
Client.SendData "Hello"  ' Encode appends vbNullChar

' Server receive (independent protocol instance per client)
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sData As String
    Client.GetData sData  ' Decode automatically parses, removes vbNullChar
    Debug.Print Client.Tag & ": " & sData
End Sub

Example 2: Multi-client concurrent demonstration

vb
' Server configuration
Private Sub Form_Load()
    Set m_oServer = New cWinsock
    m_oServer.PacketProtocol = ppDelimiter
    m_oServer.Delimiter = vbCrLf  ' Use carriage return + line feed delimiter
    m_oServer.Listen 8080
End Sub

' Client 1 sends (fragmented)
Client1.SendData "Hel"        ' Protocol instance 1 caches: "Hel"
Client1.SendData "lo" & vbCrLf  ' Protocol instance 1 parses: "Hello", clears cache

' Client 2 sends (complete)
Client2.SendData "World" & vbCrLf  ' Protocol instance 2 parses: "World", clears cache

' Client 3 sends (extra-long fragmented)
Client3.SendData "Go"            ' Protocol instance 3 caches: "Go"
Client3.SendData "od"            ' Protocol instance 3 caches: "Good"
Client3.SendData " Morn"         ' Protocol instance 3 caches: "Good Morn"
Client3.SendData "ing" & vbCrLf  ' Protocol instance 3 parses: "Good Morning", clears cache

' Server DataArrival
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sData As String
    Client.GetData sData

    ' Each client gets complete messages parsed by its own independent protocol instance
    ' Protocol instances do not interfere with each other
    Debug.Print Client.Tag & ": " & sData

    ' Output order depends on network arrival time, may be:
    ' Client 2: World
    ' Client 1: Hello
    ' Client 3: Good Morning
End Sub

Example 3: Different clients using different protocols

vb
' Server can dynamically configure each client's protocol when accepting connection
Private Sub m_oServer_ConnectionRequest(Client As cWinsock, ByRef DisConnect As Boolean)
    ' Use different protocols based on client IP or port
    Select Case Client.RemotePort
        Case 9001
            ' Client 1 uses character delimiter protocol
            Client.PacketProtocol = ppDelimiter
            Client.Delimiter = vbNullChar

        Case 9002
            ' Client 2 uses fixed length protocol
            Client.PacketProtocol = ppFixedLength
            Client.FixedLength = 10

        Case 9003
            ' Client 3 uses length header protocol
            Client.PacketProtocol = ppLengthHeader
            Client.HeaderBytes = 4
    End Select
End Sub

' Server DataArrival (each client uses its own protocol)
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sData As String
    Client.GetData sData

    ' Determine which client based on Tag, automatically use corresponding protocol to parse
    Debug.Print Client.Tag & " (" & GetProtocolName(Client) & "): " & sData
End Sub

Example 4: Sticky packet scenario demonstration

vb
' Client sends quickly in succession (may cause sticky packets)
Client.SendData "Msg1" & vbCrLf
Client.SendData "Msg2" & vbCrLf
Client.SendData "Msg3" & vbCrLf

' Server may receive all at once: "Msg1" & vbCrLf & "Msg2" & vbCrLf
' Protocol instance's Decode method will automatically split:

' First call Decode("Msg1" & vbCrLf & "Msg2" & vbCrLf)
' → Parse "Msg1"
' → Cache: "Msg2" & vbCrLf
' → Return "Msg1"

' Second call Decode("Msg3" & vbCrLf)
' → Merge cache: "Msg2" & vbCrLf & "Msg3" & vbCrLf
' → Parse "Msg2"
' → Cache: "Msg3" & vbCrLf
' → Return "Msg2"

' Third call Decode(empty data)
' → Parse "Msg3"
' → Clear cache
' → Return "Msg3"

Example 5: Packet fragmentation scenario demonstration

vb
' Client sends big data (may cause packet fragmentation)
Dim sBigData As String
sBigData = String(10000, "A") & vbCrLf
Client.SendData sBigData

' Server receives in 3 parts:
' DataArrival1: 4000 bytes "AAAA...A" (no delimiter)
' DataArrival2: 4000 bytes "AAAA...A" (no delimiter)
' DataArrival3: 2002 bytes "AAAA...A\r\n" (contains delimiter)

' Protocol instance's Decode method will automatically concatenate:

' First call Decode(4000 bytes)
' → Cache: 4000 bytes
' → No delimiter, return Empty

' Second call Decode(4000 bytes)
' → Merge cache: 8000 bytes
' → No delimiter, return Empty

' Third call Decode(2002 bytes)
' → Merge cache: 10002 bytes
' → Find vbCrLf, parse complete message
' → Clear cache
' → Return 10000 bytes "AAAA...A"

1.7 Key Points Summary

Core advantages of independent protocol instance per client:

FeatureDescription
State isolationEach client's protocol class instance maintains independent receive buffer without interference
Protocol flexibilityDifferent clients can use different protocol types and parameter configurations
Concurrency safetyIn VB6 single-threaded environment, independent state of each object is naturally safe
Memory managementAutomatically clean up its own protocol instance and buffer when client disconnects
Configuration inheritanceNew clients automatically inherit server protocol configuration while creating independent instances
Automatic managementNo need to manually manage protocol instance lifecycle, cWinsock internally handles automatically

Data flow diagram:

Client 1 Socket                      Client 2 Socket                      Client 3 Socket
      │                                   │                                   │
      ├─ Received "Hel"                   ├─ Received "Hi\0"                  ├─ Received "Tes"
      │                                   │                                   │
      ▼                                   ▼                                   ▼
Protocol instance 1.Decode          Protocol instance 2.Decode          Protocol instance 3.Decode
      │                                   │                                   │
Buffer 1: ["Hel"]                   Buffer 2: ["Hi\0"]                  Buffer 3: ["Tes"]
      │                                   │                                   │
      │                                   ▼                                   ▼
      │                              Parsed "Hi"                         Buffer 3: ["Tes"]
      │                              Clear buffer 2                            │
      │                              Trigger DataArrival                       │
      │                                   │                                   │
      ├─ Received "lo\0"                   │                                   ├─ Received "t\0"
      │                                   │                                   │
      ▼                                   │                                   ▼
Protocol instance 1.Decode                 │                           Protocol instance 3.Decode
      │                                   │                                   │
Buffer 1: ["Hello\0"]                    │                           Buffer 3: ["Test\0"]
      │                                   │                                   │
      ▼                                   │                                   ▼
Parsed "Hello"                            │                          Parsed "Test"
Clear buffer 1                           │                          Clear buffer 3
Trigger DataArrival                       │                          Trigger DataArrival

Best practice recommendations:

  1. Server configures protocol: Set server protocol configuration before Listen, all new clients automatically inherit
  2. Dynamic protocol configuration: Dynamically set protocol in ConnectionRequest event based on client characteristics (IP, port, etc.)
  3. Avoid mixing protocols: Suggest using unified protocol type for same client within its lifecycle
  4. Client close cleanup: cWinsock internally automatically cleans up protocol instances, no manual handling needed
  5. Monitor protocol status: Check if there is unprocessed fragmented data via protocol class instance's HasPendingData() method

Typical application scenarios:

  • HTTP server: Use character delimiter protocol (\r\n\r\n)
  • Binary protocol: Use length header protocol (4-byte integer)
  • Fixed format protocol: Use fixed length protocol
  • Custom protocol: Implement custom protocol class, support complex business logic

2. TCP Smart Heartbeat Mechanism (High Priority)

Feature Description: Provide automated TCP connection keep-alive and timeout disconnect mechanism.

2.1 Server Heartbeat Detection

  • Timeout mechanism

    • Default timeout: 2 minutes
    • Detection content: Last communication time (including data sending and receiving)
    • Automatically disconnect timeout clients
    • Trigger CloseEvent event
  • LastActivityTime update rules

    • Important: Must immediately reset LastActivityTime to current time after each send/receive operation to client
    • This ensures server polling won't misjudge as timeout after client skips heartbeat cycle
    • Update timing:
      • When receiving client data (DataArrival event)
      • When sending data to client (SendData/SendComplete)
      • When receiving client heartbeat
      • Any valid communication interaction
  • Implementation method

    • Timer polls all clients' LastActivityTime property
    • Automatically Close client on timeout
    • Log records (optional)
vb
' Server configuration
Public Property Let HeartbeatTimeout(ByVal lSeconds As Long)
Public Property Get HeartbeatTimeout() As Long

' Auto enable/disable
Public Property Let AutoHeartbeat(ByVal bEnable As Boolean)

' Event: client timeout disconnect
Public Event ClientTimeout(Client As cWinsock)
  • LastActivityTime update example
vb
' Update in DataArrival event
Private Sub Server_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    ' cWinsock internally automatically executes
    Client.LastActivityTime = Now  ' Or GetTickCount etc. timestamp
End Sub

' Update in SendData method
Public Sub SendData(Data As Variant, Optional ByVal CodePage As ScpEnum = ScpAcp)
    ' ... send data ...
    ' cWinsock internally automatically executes
    If IsClient() Then
        m_oParentServer.LastActivityTime = Now
    Else
        m_lLastActivityTime = Now
    End If
End Sub

2.2 Client Heartbeat Keep-Alive

  • Auto Ping mechanism

    • Default send interval: 50 seconds
    • Data content: 1 byte (customizable)
    • Smart skip: Skip current cycle if recent data send/receive exists
  • Implementation method

    • Timer controls send interval
    • Check LastActivityTime to determine if send is needed
    • SendData sends heartbeat packet
vb
' Client configuration
Public Property Let HeartbeatInterval(ByVal lSeconds As Long)
Public Property Get HeartbeatInterval() As Long

' Heartbeat packet content
Public Property Let HeartbeatData(ByVal vData As Variant)
Public Property Get HeartbeatData() As Variant

' Auto enable/disable
Public Property Let AutoHeartbeat(ByVal bEnable As Boolean)

' Event: heartbeat sent
Public Event HeartbeatSent()

2.3 Heartbeat Status Monitoring

  • Each client maintains heartbeat-related information
  • Properties:
    • LastHeartbeatTime - Last heartbeat time
    • LastActivityTime - Last communication time
    • HeartbeatCount - Heartbeat count
    • IsAlive - Whether alive

3. GetData Enhanced Methods (Medium Priority)

Feature Description: Provide more convenient data retrieval methods, supporting different format outputs.

3.1 Design Principles

Important distinction:

  • Original GetData uses byref parameter to output data
  • Enhanced methods output data via return value
  • Convenient to write in one line of code, e.g., Dim Data As String: Data = GetDataText()

3.2 New Methods

vb
' Get text string (using default encoding ACP)
Public Function GetDataText(Optional ByVal MaxLen As Long = -1) As String

' Get text string (specify encoding)
Public Function GetDataTextEx(Optional ByVal CodePage As ScpEnum = ScpAcp, Optional ByVal MaxLen As Long = -1) As String

' Get UTF-8 string
Public Function GetDataTextUTF8(Optional ByVal MaxLen As Long = -1) As String

' Get Unicode string
Public Function GetDataTextUnicode(Optional ByVal MaxLen As Long = -1) As String

' Get hex string (space separated)
Public Function GetDataHex(Optional ByVal MaxLen As Long = -1) As String

' Get byte array
Public Function GetDataByteArray(Optional ByVal MaxLen As Long = -1) As Byte()

3.3 Usage Examples

One-line code style:

vb
' Direct assignment, no need to declare and pass byref
Debug.Print GetDataText()                              ' Output text
Debug.Print GetDataHex()                               ' Output: 48 65 6C 6C 6F
Debug.Print GetDataTextUTF8()                          ' Output UTF-8 text

' Check data
If GetDataText() = "Hello" Then
    Debug.Print "Received Hello"
End If

' Process data
Dim sReply As String
sReply = ProcessData(GetDataText())

' Assign to variable
Dim sData As String: sData = GetDataText()
Dim baData() As Byte: baData = GetDataByteArray()

Comparison with original GetData:

vb
' Original way (need to declare and pass byref)
Dim sData As String
Client.GetData sData
Debug.Print sData

' New way (direct return)
Debug.Print Client.GetDataText()

' Original way (byte array)
Dim baData() As Byte
Client.GetData baData

' New way (direct return)
Dim baData() As Byte
baData = Client.GetDataByteArray()

With MaxLen parameter:

vb
' Only read first 100 bytes
Debug.Print Client.GetDataText(100)

' Get hex representation of first 50 bytes
Debug.Print Client.GetDataHex(50)

3.4 Implementation Details

Internal implementation:

vb
Public Function GetDataText(Optional ByVal MaxLen As Long = -1) As String
    Dim sData As String
    GetData sData, vbString, MaxLen, ScpAcp  ' Call original GetData
    GetDataText = sData                      ' Return via return value
End Function

Public Function GetDataHex(Optional ByVal MaxLen As Long = -1) As String
    Dim baData() As Byte
    Dim i As Long
    Dim sHex As String
    
    ' Get byte array
    GetData baData, vbByte + vbArray, MaxLen
    
    ' Convert to hex string
    For i = LBound(baData) To UBound(baData)
        sHex = sHex & Right$("0" & Hex$(baData(i)), 2) & " "
    Next
    
    ' Remove trailing space
    If Len(sHex) > 0 Then
        GetDataHex = Left$(sHex, Len(sHex) - 1)
    End If
End Function

Buffer consistency:

  • All enhanced methods internally call original GetData
  • Maintain same buffer behavior as original method
  • After partial read, remaining data is still retained in internal buffer

4. Performance Optimization (Medium Priority)

4.1 Batch Send

vb
' Batch send multiple messages, reduce system calls
Public Sub SendBatch(vData As Variant)

4.2 Data Compression

  • Optional compression algorithm support
  • Automatic compression for large data
  • Transparent compression/decompression

4.3 Connection Pool

  • Reuse TCP connections
  • Reduce Connect overhead
  • Automatic load balancing

5. Advanced Features (Low Priority)

5.1 SSL/TLS Encryption

  • Support HTTPS/WSS
  • Certificate verification
  • Secure handshake

5.2 WebSocket Protocol

  • Complete WebSocket support
  • Handshake and frame processing
  • Auto Ping/Pong

5.3 Auto Reconnect

  • Automatic reconnection mechanism
  • Exponential backoff algorithm
  • Maximum retry count

5.4 Rate Limiting

  • Send rate limit
  • Receive rate limit
  • Traffic statistics

📊 Development Priorities

P0 - Core Features (Must Implement)

  1. Data Packet Protocol

    • Solve most common data fragmentation issues
    • Improve development efficiency
    • Reduce error rate
  2. TCP Smart Heartbeat

    • Ensure connection stability
    • Timely cleanup zombie connections
    • Suitable for production environment

P1 - Enhanced Features (Important)

  1. GetData Enhanced Methods
    • Improve development experience
    • Reduce code amount
    • Reduce error probability

P2 - Optimization Features (Optional)

  1. Performance Optimization
    • Batch send
    • Data compression
    • Connection pool

P3 - Advanced Features (Long-term Planning)

  1. SSL/TLS Encryption
  2. WebSocket Protocol
  3. Auto Reconnect
  4. Rate Limiting

🗺️ Technical Roadmap

Phase 1: Packet Protocol Implementation (Estimated 3-5 days)

  • Day 1-2: Design protocol interface and data structures
  • Day 3-4: Implement built-in protocols (CRLF, fixed length, length header)
  • Day 5: Implement custom protocol interface and testing

Phase 2: Heartbeat Mechanism Implementation (Estimated 2-3 days)

  • Day 1-2: Implement server timeout detection
  • Day 3: Implement client heartbeat keep-alive

Phase 3: GetData Enhancement (Estimated 1 day)

  • Day 1: Implement 4 new methods and testing

Phase 4: Performance Optimization (Estimated 2-3 days)

  • Day 1: Batch send implementation
  • Day 2: Data compression implementation
  • Day 3: Connection pool design

Phase 5: Advanced Features (Long-term)

  • Gradually implement based on user needs and feedback

📝 Usage Recommendations

During Development

  • Maintain backward compatibility
  • Don't affect existing functionality
  • Provide sufficient unit tests
  • Update documentation and examples

Release Strategy

  • Phased release
  • Collect user feedback
  • Continuous optimization and improvement


Last updated: 2026-01-10

VB6 and LOGO copyright of Microsoft Corporation