Skip to content

cWinsock Synchronous Methods Detailed Guide

📋 Table of Contents


Overview

cWinsock provides a complete set of synchronous (blocking) network operation methods, allowing developers to perform network communication without using the event-driven model. Synchronous methods block the current thread until the operation completes, times out, or an error occurs.

Core Features

  • ⏱️ Timeout Control - All synchronous operations support timeout settings
  • 🔄 Message Pump Mechanism - Processes message queue via PeekMessage/DispatchMessage, does not block UI
  • 🎯 Simple API - Functional calls, returns Boolean to indicate success/failure
  • 🌐 Comprehensive Support - Covers connection, send, receive, event waiting
  • 💻 Flexible Encoding - Supports multiple text encodings (ACP/GBK, UTF-8, Unicode)

Applicable Scenarios

  • Simple client applications (e.g., HTTP client)
  • Network operations that need to execute sequentially
  • Scenarios without complex event handling
  • Rapid prototype development

Synchronous Methods List

Method NameReturn TypeDescription
SyncConnectBooleanSynchronously connect to remote server
SyncSendTextBooleanSynchronously send string
SyncSendArrayBooleanSynchronously send byte array
SyncSendBooleanSynchronously send buffer data
SyncReceiveTextStringSynchronously receive string
SyncReceiveArrayBooleanSynchronously receive to byte array
SyncReceiveBooleanSynchronously receive to buffer
SyncWaitForEventBooleanWait for specified socket event
SyncCancelWaitSubCancel waiting operation

Event Mask Enumeration

WinSocketEventMaskEnum is used to specify the event types to wait for in SyncWaitForEvent.

Enumeration Values

Enum NameValueDescription
wskSfdRead2^0Readable event
wskSfdWrite2^1Writable event
wskSfdOob2^2Out-of-band data
wskSfdAccept2^3Accept connection
wskSfdConnect2^4Connection completed
wskSfdClose2^5Connection closed
wskSfdAll2^6 - 1All events (default)
[_wskSfdResolve]2^15Internal: Domain name resolution
[_wskSfdForceRead]2^14Internal: Force read

Usage Example

vb
' Wait for readable event
If ws.SyncWaitForEvent(5000, wskSfdRead) Then
    Debug.Print "Socket readable"
End If

' Wait for writable or readable event
If ws.SyncWaitForEvent(5000, wskSfdRead Or wskSfdWrite) Then
    Debug.Print "Socket ready"
End If

' Wait for any event
If ws.SyncWaitForEvent(5000, wskSfdAll) Then
    Debug.Print "Event triggered"
End If

Methods Detailed

SyncConnect - Synchronous Connect

Description

Synchronously connect to the specified remote server with timeout control. Returns True on successful connection, False on timeout or failure.

Syntax

vb
Public Function SyncConnect(HostAddress As String, ByVal HostPort As Long, Optional ByVal TimeOut As Long) As Boolean

Parameters

ParameterTypeDescription
HostAddressStringRemote host name or IP address
HostPortLongRemote port number
TimeOutLong (Optional)Timeout in milliseconds, uses underlying default value if not specified

Return Value

  • True - Connection successful
  • False - Connection failed or timed out

Usage Example

vb
Private Sub TestSyncConnect()
    Dim ws As New cWinsock
    Dim bResult As Boolean

    ' Connect to example.com port 80, timeout 5 seconds
    bResult = ws.SyncConnect("example.com", 80, 5000)

    If bResult Then
        Debug.Print "Connected successfully!"
        Debug.Print "Remote IP: " & ws.RemoteHostIP
        Debug.Print "Local IP: " & ws.LocalIP
        Debug.Print "Local Port: " & ws.LocalPort
    Else
        Debug.Print "Connection failed or timed out"
    End If

    ws.Close_
End Sub

Error Handling

vb
Private Sub TestConnectWithError()
    Dim ws As New cWinsock

    On Error GoTo EH

    If ws.SyncConnect("invalid-host-name-12345.com", 80, 3000) Then
        Debug.Print "Connected successfully"
    Else
        Debug.Print "Connection failed"
    End If

    Exit Sub

EH:
    Debug.Print "Connection error: " & Err.Description & " (Error number: " & Err.Number & ")"
    ws.Close_
End Sub

SyncSendText - Synchronous Send Text

Description

Synchronously send string data with timeout control.

Syntax

vb
Public Function SyncSendText( _
    Text As String, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional ByVal HostPort As Long, _
    Optional ByVal CodePage As EnumScpCodePage = wcpUtf8) As Boolean

Parameters

ParameterTypeDescription
TextStringText to send
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Target host address (for UDP server mode)
HostPortLong (Optional)Target port (for UDP server mode)
CodePageEnumScpCodePage (Optional)Text encoding, default wcpUtf8

Return Value

  • True - Send successful
  • False - Send failed or timed out

Usage Example

vb
Private Sub TestSyncSendText()
    Dim ws As New cWinsock

    ' Connect
    If ws.SyncConnect("example.com", 80, 5000) Then
        ' Send HTTP request
        Dim sRequest As String
        sRequest = "GET / HTTP/1.1" & vbCrLf & _
                   "Host: example.com" & vbCrLf & vbCrLf

        If ws.SyncSendText(sRequest, 5000, , , wcpUtf8) Then
            Debug.Print "Send successful"
        Else
            Debug.Print "Send failed"
        End If
    End If

    ws.Close_
End Sub

Using Different Encodings

vb
' Use GBK encoding (default)
ws.SyncSendText "中文测试", 5000, , , wcpAcp

' Use UTF-8 encoding (recommended)
ws.SyncSendText "中文测试", 5000, , , wcpUtf8

' Use Unicode (no conversion)
ws.SyncSendText "中文测试", 5000, , , wcpUnicode

SyncSendArray - Synchronous Send Byte Array

Description

Synchronously send byte array data with timeout control.

Syntax

vb
Public Function SyncSendArray( _
    Buffer() As Byte, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional ByVal HostPort As Long, _
    Optional ByVal Flags As Long = 0) As Boolean

Parameters

ParameterTypeDescription
BufferByte()Byte array to send
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Target host address
HostPortLong (Optional)Target port
FlagsLong (Optional)Send flags

Return Value

  • True - Send successful
  • False - Send failed or timed out

Usage Example

vb
Private Sub TestSyncSendArray()
    Dim ws As New cWinsock
    Dim baData() As Byte

    ' Prepare data
    baData = StrConv("Hello World", vbFromUnicode)

    ' Connect and send
    If ws.SyncConnect("127.0.0.1", 8080, 5000) Then
        If ws.SyncSendArray(baData, 5000) Then
            Debug.Print "Byte array sent successfully"
        End If
    End If

    ws.Close_
End Sub

SyncSend - Synchronous Send Buffer

Description

Synchronously send data from a specified buffer pointer, for high-performance scenarios.

Syntax

vb
Public Function SyncSend( _
    ByVal BufPtr As Long, _
    ByVal BufLen As Long, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional ByVal HostPort As Long, _
    Optional ByVal Flags As Long = 0) As Boolean

Parameters

ParameterTypeDescription
BufPtrLongBuffer pointer
BufLenLongBuffer length
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Target host address
HostPortLong (Optional)Target port
FlagsLong (Optional)Send flags

Return Value

  • True - Send successful
  • False - Send failed or timed out

Usage Example

vb
' Note: This method requires memory pointer operations, usually for advanced scenarios
Private Sub TestSyncSend()
    Dim ws As New cWinsock
    Dim sData As String
    Dim lPtr As Long

    sData = "Hello World"

    ' Get string pointer (using StrPtr)
    lPtr = StrPtr(sData)

    If ws.SyncConnect("127.0.0.1", 8080, 5000) Then
        If ws.SyncSend(lPtr, LenB(sData), 5000) Then
            Debug.Print "Send successful"
        End If
    End If

    ws.Close_
End Sub

SyncReceiveText - Synchronous Receive Text

Description

Synchronously receive text data with timeout control. Can specify the minimum number of bytes to receive.

Syntax

vb
Public Function SyncReceiveText( _
    Optional ByVal NeedLen As Long = 1, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional HostPort As Long, _
    Optional ByVal CodePage As EnumScpCodePage = wcpUtf8) As String

Parameters

ParameterTypeDescription
NeedLenLong (Optional)Minimum bytes to receive, default 1
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Source host address (for UDP mode)
HostPortLong (Optional)Source port (for UDP mode)
CodePageEnumScpCodePage (Optional)Text encoding, default wcpUtf8

Return Value

  • Success: Returns received text
  • Failure: Returns empty string

Usage Example

vb
Private Sub TestSyncReceiveText()
    Dim ws As New cWinsock
    Dim sResponse As String

    ' Connect
    If ws.SyncConnect("example.com", 80, 5000) Then
        ' Send request
        Dim sRequest As String
        sRequest = "GET / HTTP/1.1" & vbCrLf & _
                   "Host: example.com" & vbCrLf & vbCrLf

        If ws.SyncSendText(sRequest, 5000, , , wcpUtf8) Then
            ' Receive response (at least 100 bytes, timeout 5 seconds)
            sResponse = ws.SyncReceiveText(100, 5000, , , wcpUtf8)

            If Len(sResponse) > 0 Then
                Debug.Print "Response received:"
                Debug.Print sResponse
                Debug.Print "Length: " & Len(sResponse) & " characters"
            Else
                Debug.Print "Receive failed or timed out"
            End If
        End If
    End If

    ws.Close_
End Sub

Read Fixed Length

vb
' Read first 100 bytes
Dim sHeader As String
sHeader = ws.SyncReceiveText(100, 3000, , , wcpUtf8)
Debug.Print "Header: " & sHeader

SyncReceiveArray - Synchronous Receive Byte Array

Description

Synchronously receive byte array data with timeout control.

Syntax

vb
Public Function SyncReceiveArray( _
    Buffer() As Byte, _
    Optional ByVal NeedLen As Long, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional ByVal HostPort As Long, _
    Optional ByVal Flags As Long = 0) As Boolean

Parameters

ParameterTypeDescription
BufferByte()Byte array to receive data
NeedLenLong (Optional)Minimum bytes to receive
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Source host address
HostPortLong (Optional)Source port
FlagsLong (Optional)Receive flags

Return Value

  • True - Receive successful
  • False - Receive failed or timed out

Usage Example

vb
Private Sub TestSyncReceiveArray()
    Dim ws As New cWinsock
    Dim baBuffer() As Byte

    ' Connect
    If ws.SyncConnect("127.0.0.1", 8080, 5000) Then
        ' Send request
        If ws.SyncSendText("GET_DATA", 5000, , , wcpUtf8) Then
            ' Receive response (max 8192 bytes)
            ReDim baBuffer(0 To 8191) As Byte

            If ws.SyncReceiveArray(baBuffer, 1, 5000) Then
                ' Get actual received length
                Dim lReceived As Long
                lReceived = UBound(baBuffer) + 1
                Debug.Print "Received " & lReceived & " bytes"
            Else
                Debug.Print "Receive failed or timed out"
            End If
        End If
    End If

    ws.Close_
End Sub

SyncReceive - Synchronous Receive to Buffer

Description

Synchronously receive data from socket to a specified buffer pointer, for high-performance scenarios.

Syntax

vb
Public Function SyncReceive( _
    ByVal BufPtr As Long, _
    ByVal BufLen As Long, _
    ByRef Received As Long, _
    Optional ByVal TimeOut As Long, _
    Optional HostAddress As String, _
    Optional ByVal HostPort As Long, _
    Optional ByVal Flags As Long = 0) As Boolean

Parameters

ParameterTypeDescription
BufPtrLongBuffer pointer
BufLenLongBuffer length
ReceivedLong (ByRef)Actual bytes received
TimeOutLong (Optional)Timeout in milliseconds
HostAddressString (Optional)Source host address
HostPortLong (Optional)Source port
FlagsLong (Optional)Receive flags

Return Value

  • True - Receive successful, Received contains actual bytes received
  • False - Receive failed or timed out

Usage Example

vb
Private Sub TestSyncReceive()
    Dim ws As New cWinsock
    Dim baBuffer() As Byte
    Dim lReceived As Long

    ' Prepare buffer
    ReDim baBuffer(0 To 8191) As Byte

    ' Connect
    If ws.SyncConnect("127.0.0.1", 8080, 5000) Then
        ' Send request
        If ws.SyncSendText("GET_DATA", 5000, , , wcpUtf8) Then
            ' Receive response
            If ws.SyncReceive(VarPtr(baBuffer(0)), 8192, lReceived, 5000) Then
                Debug.Print "Actually received: " & lReceived & " bytes"

                ' Only use actually received portion
                If lReceived > 0 Then
                    ReDim Preserve baBuffer(0 To lReceived - 1)
                End If
            Else
                Debug.Print "Receive failed or timed out"
            End If
        End If
    End If

    ws.Close_
End Sub

SyncWaitForEvent - Wait for Event

Description

Wait for specified socket event to occur with timeout control. Can be used to poll for specific events or implement custom protocols.

Syntax

vb
Public Function SyncWaitForEvent( _
    ByVal TimeOut As Long, _
    Optional ByVal EventMask As WinSocketEventMaskEnum = wskSfdAll) As Boolean

Parameters

ParameterTypeDescription
TimeOutLongTimeout in milliseconds
EventMaskWinSocketEventMaskEnum (Optional)Event mask, default wskSfdAll

Return Value

  • True - Specified event occurred
  • False - Timeout or error

Usage Example

vb
Private Sub TestWaitForEvent()
    Dim ws As New cWinsock

    ' Connect
    If ws.SyncConnect("example.com", 80, 5000) Then
        ' Wait for writable event (indicates socket ready to send data)
        If ws.SyncWaitForEvent(5000, wskSfdWrite) Then
            Debug.Print "Socket writable, can send data"

            ' Send data
            ws.SyncSendText "Hello", 5000, , , wcpUtf8
        End If

        ' Wait for readable event (indicates data available to read)
        If ws.SyncWaitForEvent(5000, wskSfdRead) Then
            Debug.Print "Socket readable, can receive data"

            Dim sData As String
            sData = ws.SyncReceiveText(1, 5000, , , wcpUtf8)
            Debug.Print "Received: " & sData
        End If
    End If

    ws.Close_
End Sub

Wait for Multiple Events

vb
' Wait for readable or writable event
Dim lMask As Long
lMask = wskSfdRead Or wskSfdWrite

If ws.SyncWaitForEvent(5000, lMask) Then
    ' Check BytesReceived to determine which event
    If ws.BytesReceived > 0 Then
        Debug.Print "Data available to read"
    Else
        Debug.Print "Socket writable"
    End If
End If

SyncCancelWait - Cancel Wait

Description

Cancel the currently running synchronous wait operation (such as SyncWaitForEvent, SyncReceiveText, etc.).

Syntax

vb
Public Sub SyncCancelWait()

Usage Scenarios

  • Cancel ongoing network operations when form closes
  • Interrupt wait when user cancels operation
  • Notify stop in multi-threaded scenarios

Usage Example

vb
Private WithEvents m_oWinsock As cWinsock
Private m_bCancelled As Boolean

Private Sub cmdStart_Click()
    Set m_oWinsock = New cWinsock

    If m_oWinsock.SyncConnect("example.com", 80, 5000) Then
        ' Start waiting for data
        Dim sData As String
        m_bCancelled = False

        Do
            ' Check if cancelled
            If m_bCancelled Then
                Debug.Print "User cancelled operation"
                m_oWinsock.SyncCancelWait
                Exit Do
            End If

            ' Receive data
            sData = m_oWinsock.SyncReceiveText(1, 1000, , , wcpUtf8)

            If Len(sData) > 0 Then
                Debug.Print "Received: " & sData
            Else
                Debug.Print "Timeout, continuing to wait..."
            End If

            DoEvents  ' Allow UI to respond
        Loop Until False
    End If

    m_oWinsock.Close_
End Sub

Private Sub cmdCancel_Click()
    m_bCancelled = True
End Sub

Private Sub Form_Unload(Cancel As Integer)
    ' Cancel wait when form closes
    If Not m_oWinsock Is Nothing Then
        m_oWinsock.SyncCancelWait
        m_oWinsock.Close_
    End If
End Sub

Usage Scenarios

Scenario 1: HTTP Client

vb
Private Function HttpGet(ByVal sUrl As String, ByVal sPath As String) As String
    Dim ws As New cWinsock
    Dim sHost As String
    Dim nPort As Long
    Dim sRequest As String
    Dim sResponse As String

    ' Parse URL (simplified)
    sHost = ExtractHost(sUrl)
    nPort = ExtractPort(sUrl, 80)

    ' Connect
    If Not ws.SyncConnect(sHost, nPort, 5000) Then
        HttpGet = "Connection failed"
        Exit Function
    End If

    ' Build request
    sRequest = "GET " & sPath & " HTTP/1.1" & vbCrLf & _
               "Host: " & sHost & vbCrLf & _
               "Connection: close" & vbCrLf & vbCrLf

    ' Send request
    If Not ws.SyncSendText(sRequest, 5000, , , wcpUtf8) Then
        HttpGet = "Send failed"
        ws.Close_
        Exit Function
    End If

    ' Receive response
    sResponse = ws.SyncReceiveText(1, 5000, , , wcpUtf8)

    ws.Close_
    HttpGet = sResponse
End Function

' Usage
Dim sHtml As String
sHtml = HttpGet("http://example.com", "/")
Debug.Print sHtml

Scenario 2: Echo Client

vb
Private Sub EchoClient()
    Dim ws As New cWinsock

    ' Connect to Echo server
    If ws.SyncConnect("127.0.0.1", 7, 5000) Then
        Debug.Print "Connected to Echo server"

        ' Send message
        Dim sMessage As String
        sMessage = "Hello, Echo Server!"

        If ws.SyncSendText(sMessage, 5000, , , wcpUtf8) Then
            Debug.Print "Sent: " & sMessage

            ' Receive echo
            Dim sReply As String
            sReply = ws.SyncReceiveText(Len(sMessage), 5000, , , wcpUtf8)

            Debug.Print "Received: " & sReply
        End If
    End If

    ws.Close_
End Sub

Scenario 3: File Upload (Simplified)

vb
Private Sub UploadFile(ByVal sFilePath As String, ByVal sServer As String, ByVal nPort As Long)
    Dim ws As New cWinsock
    Dim baBuffer() As Byte
    Dim nFileNum As Integer
    Dim lFileSize As Long
    Dim lOffset As Long
    Dim lChunkSize As Long

    ' Connect to server
    If Not ws.SyncConnect(sServer, nPort, 5000) Then
        Debug.Print "Connection failed"
        Exit Sub
    End If

    ' Open file
    nFileNum = FreeFile
    Open sFilePath For Binary As #nFileNum
    lFileSize = LOF(nFileNum)

    ' Send file header
    Dim sHeader As String
    sHeader = "UPLOAD:" & CStr(lFileSize) & vbCrLf
    ws.SyncSendText sHeader, 5000, , , wcpUtf8

    ' Send in chunks
    lChunkSize = 8192 ' 8KB per chunk
    lOffset = 1

    Do While lOffset <= lFileSize
        ReDim baBuffer(0 To lChunkSize - 1) As Byte
        Get #nFileNum, lOffset, baBuffer

        ' Adjust last chunk size
        If lOffset + lChunkSize > lFileSize + 1 Then
            ReDim Preserve baBuffer(0 To lFileSize + 1 - lOffset) As Byte
        End If

        ' Send chunk
        If Not ws.SyncSendArray(baBuffer, 5000) Then
            Debug.Print "Send failed at offset: " & lOffset
            Exit Do
        End If

        lOffset = lOffset + lChunkSize

        ' Update progress
        Debug.Print "Sent: " & Format((lOffset - 1) / lFileSize * 100, "0.00") & "%"
        DoEvents
    Loop

    Close #nFileNum
    ws.Close_
    Debug.Print "Upload complete"
End Sub

Async vs Sync

Async Event-Driven Mode

Advantages:

  • ✅ Does not block UI thread
  • ✅ Suitable for high-concurrency scenarios
  • ✅ Timely response
  • ✅ Can handle multiple clients

Disadvantages:

  • ❌ Code scattered across multiple events
  • ❌ Logic flow not intuitive
  • ❌ Need to maintain state variables
vb
' Async mode
Private WithEvents ws As cWinsock
Private m_bWaiting As Boolean
Private m_sResponse As String

Private Sub cmdConnect_Click()
    Set ws = New cWinsock
    ws.Connect "example.com", 80
    m_bWaiting = True
    Do While m_bWaiting
        DoEvents
    Loop
End Sub

Private Sub ws_Connect(Client As cWinsock)
    Client.SendData "GET / HTTP/1.1" & vbCrLf
End Sub

Private Sub ws_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Client.GetData m_sResponse
    m_bWaiting = False
End Sub

Sync Blocking Mode

Advantages:

  • ✅ Linear code, clear logic
  • ✅ Easy to understand and debug
  • ✅ Suitable for simple sequential operations
  • ✅ No need to maintain state variables

Disadvantages:

  • ❌ Blocks current execution flow
  • ❌ Not suitable for high concurrency
  • ❌ Need to manually call DoEvents to maintain UI responsiveness
vb
' Sync mode
Private Sub cmdConnect_Click()
    Dim ws As New cWinsock

    ' Connect
    If ws.SyncConnect("example.com", 80, 5000) Then
        ' Send
        If ws.SyncSendText("GET / HTTP/1.1" & vbCrLf, 5000, , , wcpUtf8) Then
            ' Receive
            Dim sResponse As String
            sResponse = ws.SyncReceiveText(1, 5000, , , wcpUtf8)

            Debug.Print sResponse
        End If
    End If

    ws.Close_
End Sub

Selection Recommendations

ScenarioRecommended ModeReason
Simple HTTP clientSyncSequential operations, simple logic
TCP serverAsyncNeed to handle multiple clients
High-concurrency applicationsAsyncAvoid blocking
Rapid prototypingSyncFast development
File transferSyncSimple request-response
Real-time communicationAsyncTimely response

Important Notes

⚠️ Important Considerations

  1. Message Pump Mechanism

    • Synchronous methods use PeekMessage/DispatchMessage internally to process message queue
    • Does not block UI message loop, forms can still respond
    • No need to manually call DoEvents
  2. Timeout Settings

    • Recommend setting reasonable timeout for all synchronous operations
    • Adjust timeout based on network environment (recommend 3-30 seconds)
    • Automatically returns failure status on timeout
  3. Error Handling

    • All synchronous methods should be used with On Error
    • Check return value to determine if operation was successful
    • Use GetErrorDescription to get error description
  4. Resource Cleanup

    • Be sure to call Close_ after operations complete
    • Cancel ongoing wait operations when form unloads
    • Use SyncCancelWait to interrupt long waits
  5. Encoding Issues

    • Default encoding is wcpUtf8
    • Ensure send and receive use the same encoding
    • Clearly specify encoding protocol when communicating with other systems
  6. State Checking

    • Ensure socket is connected before calling synchronous methods
    • Use State property to check connection status
    • Use BytesReceived to check available data

⚠️ Performance Considerations

  1. Avoid Frequent Small Data Sends

    • Merge small data blocks together
    • Use buffer for batch processing
  2. Set Reasonable Timeout

    • Too short timeout may cause false judgments
    • Too long timeout reduces response speed
  3. Memory Management

    • Release large byte arrays promptly
    • Avoid repeated memory allocation in loops

⚠️ Thread Safety

  • Synchronous methods are NOT supported in multi-threaded scenarios
  • All operations should be executed in the main thread
  • Do not call synchronous methods in background threads

Complete Examples

Complete HTTP Client Example

vb
' Form1.frm
Option Explicit

Private WithEvents m_oWinsock As cWinsock
Private m_bCancelled As Boolean

Private Sub cmdGet_Click()
    Dim sUrl As String
    Dim sHost As String
    Dim nPort As Long
    Dim sPath As String
    Dim sRequest As String
    Dim sResponse As String

    ' Get URL
    sUrl = txtUrl.Text

    ' Parse URL
    ParseUrl sUrl, sHost, nPort, sPath

    If Len(sHost) = 0 Then
        MsgBox "Invalid URL", vbExclamation
        Exit Sub
    End If

    ' Create socket
    Set m_oWinsock = New cWinsock
    m_bCancelled = False

    ' Disable buttons
    cmdGet.Enabled = False
    cmdCancel.Enabled = True

    ' Connect
    If Not m_oWinsock.SyncConnect(sHost, nPort, 5000) Then
        MsgBox "Connection failed: " & m_oWinsock.GetErrorDescription(Err.LastDllError), vbExclamation
        ResetUI
        Exit Sub
    End If

    Debug.Print "Connected to " & sHost & ":" & nPort

    ' Check cancel
    If m_bCancelled Then
        ResetUI
        Exit Sub
    End If

    ' Build request
    sRequest = "GET " & sPath & " HTTP/1.1" & vbCrLf & _
               "Host: " & sHost & vbCrLf & _
               "User-Agent: cWinsock/1.0" & vbCrLf & _
               "Connection: close" & vbCrLf & vbCrLf

    ' Send request
    If Not m_oWinsock.SyncSendText(sRequest, 5000, , , wcpUtf8) Then
        MsgBox "Send failed", vbExclamation
        ResetUI
        Exit Sub
    End If

    Debug.Print "Request sent"

    ' Check cancel
    If m_bCancelled Then
        ResetUI
        Exit Sub
    End If

    ' Receive response
    sResponse = m_oWinsock.SyncReceiveText(1, 10000, , , wcpUtf8)

    If Len(sResponse) > 0 Then
        Debug.Print "Response received, length: " & Len(sResponse)
        txtResponse.Text = sResponse
    Else
        MsgBox "Receive timeout or failed", vbExclamation
    End If

    ' Cleanup
    ResetUI
End Sub

Private Sub cmdCancel_Click()
    m_bCancelled = True
    If Not m_oWinsock Is Nothing Then
        m_oWinsock.SyncCancelWait
    End If
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If Not m_oWinsock Is Nothing Then
        m_oWinsock.SyncCancelWait
        m_oWinsock.Close_
        Set m_oWinsock = Nothing
    End If
End Sub

Private Sub ResetUI()
    If Not m_oWinsock Is Nothing Then
        m_oWinsock.Close_
        Set m_oWinsock = Nothing
    End If
    cmdGet.Enabled = True
    cmdCancel.Enabled = False
End Sub

Private Sub ParseUrl(ByVal sUrl As String, ByRef sHost As String, ByRef nPort As Long, ByRef sPath As String)
    Dim sTemp As String
    Dim nPos As Long
    Dim nPortPos As Long
    Dim nPathPos As Long

    ' Remove protocol prefix
    If InStr(1, sUrl, "://") > 0 Then
        sUrl = Mid$(sUrl, InStr(sUrl, "://") + 3)
    End If

    ' Find path start position
    nPathPos = InStr(1, sUrl, "/")
    If nPathPos = 0 Then
        nPathPos = Len(sUrl) + 1
    End If

    ' Extract host and port
    sTemp = Left$(sUrl, nPathPos - 1)

    ' Find port
    nPortPos = InStr(1, sTemp, ":")
    If nPortPos > 0 Then
        sHost = Left$(sTemp, nPortPos - 1)
        nPort = Val(Mid$(sTemp, nPortPos + 1))
    Else
        sHost = sTemp
        nPort = 80
    End If

    ' Extract path
    sPath = Mid$(sUrl, nPathPos)
    If Len(sPath) = 0 Then
        sPath = "/"
    End If
End Sub

Simple Chat Client Example

vb
Private WithEvents m_oWinsock As cWinsock

Private Sub cmdConnect_Click()
    Set m_oWinsock = New cWinsock

    If m_oWinsock.SyncConnect(txtServer.Text, Val(txtPort.Text), 5000) Then
        Debug.Print "Connected to server"
        txtSend.Enabled = True
        cmdConnect.Enabled = False
        cmdDisconnect.Enabled = True
    Else
        MsgBox "Connection failed", vbExclamation
    End If
End Sub

Private Sub cmdDisconnect_Click()
    If Not m_oWinsock Is Nothing Then
        m_oWinsock.SyncCancelWait
        m_oWinsock.Close_
        Set m_oWinsock = Nothing
    End If

    txtSend.Enabled = False
    cmdConnect.Enabled = True
    cmdDisconnect.Enabled = False
End Sub

Private Sub cmdSend_Click()
    If m_oWinsock Is Nothing Then Exit Sub

    Dim sMessage As String
    sMessage = "[" & txtNick.Text & "]: " & txtSend.Text

    If m_oWinsock.SyncSendText(sMessage, 5000, , , wcpUtf8) Then
        txtReceive.Text = txtReceive.Text & sMessage & vbCrLf
        txtSend.Text = ""
    Else
        MsgBox "Send failed", vbExclamation
    End If
End Sub

Private Sub tmrReceive_Timer()
    If m_oWinsock Is Nothing Or m_oWinsock.State <> sckConnected Then Exit Sub

    ' Check if data available
    If m_oWinsock.BytesReceived > 0 Then
        Dim sData As String
        sData = m_oWinsock.SyncReceiveText(1, 100, , , wcpUtf8)

        If Len(sData) > 0 Then
            txtReceive.Text = txtReceive.Text & sData & vbCrLf
            txtReceive.SelStart = Len(txtReceive.Text)
        End If
    End If
End Sub

Summary

The synchronous methods of cWinsock provide a simple, intuitive way of network programming, especially suitable for:

  • 🎯 Simple Client Applications - HTTP, Echo, Chat, etc.
  • 📚 Learning Network Programming - Linear code is easy to understand
  • Rapid Prototyping - Quickly validate ideas
  • 🔄 Sequential Operations - Tasks that need to be executed step by step

For more complex servers or high-concurrency scenarios, it is recommended to use the asynchronous event-driven mode.


Last Updated: 2026-01-26

VB6 and LOGO copyright of Microsoft Corporation