cWinsock Synchronous Methods Detailed Guide
📋 Table of Contents
- Overview
- Synchronous Methods List
- Event Mask Enumeration
- Methods Detailed
- Usage Scenarios
- Async vs Sync
- Important Notes
- Complete Examples
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 Name | Return Type | Description |
|---|---|---|
SyncConnect | Boolean | Synchronously connect to remote server |
SyncSendText | Boolean | Synchronously send string |
SyncSendArray | Boolean | Synchronously send byte array |
SyncSend | Boolean | Synchronously send buffer data |
SyncReceiveText | String | Synchronously receive string |
SyncReceiveArray | Boolean | Synchronously receive to byte array |
SyncReceive | Boolean | Synchronously receive to buffer |
SyncWaitForEvent | Boolean | Wait for specified socket event |
SyncCancelWait | Sub | Cancel waiting operation |
Event Mask Enumeration
WinSocketEventMaskEnum is used to specify the event types to wait for in SyncWaitForEvent.
Enumeration Values
| Enum Name | Value | Description |
|---|---|---|
wskSfdRead | 2^0 | Readable event |
wskSfdWrite | 2^1 | Writable event |
wskSfdOob | 2^2 | Out-of-band data |
wskSfdAccept | 2^3 | Accept connection |
wskSfdConnect | 2^4 | Connection completed |
wskSfdClose | 2^5 | Connection closed |
wskSfdAll | 2^6 - 1 | All events (default) |
[_wskSfdResolve] | 2^15 | Internal: Domain name resolution |
[_wskSfdForceRead] | 2^14 | Internal: Force read |
Usage Example
' 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 IfMethods 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
Public Function SyncConnect(HostAddress As String, ByVal HostPort As Long, Optional ByVal TimeOut As Long) As BooleanParameters
| Parameter | Type | Description |
|---|---|---|
HostAddress | String | Remote host name or IP address |
HostPort | Long | Remote port number |
TimeOut | Long (Optional) | Timeout in milliseconds, uses underlying default value if not specified |
Return Value
True- Connection successfulFalse- Connection failed or timed out
Usage Example
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 SubError Handling
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 SubSyncSendText - Synchronous Send Text
Description
Synchronously send string data with timeout control.
Syntax
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 BooleanParameters
| Parameter | Type | Description |
|---|---|---|
Text | String | Text to send |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Target host address (for UDP server mode) |
HostPort | Long (Optional) | Target port (for UDP server mode) |
CodePage | EnumScpCodePage (Optional) | Text encoding, default wcpUtf8 |
Return Value
True- Send successfulFalse- Send failed or timed out
Usage Example
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 SubUsing Different Encodings
' Use GBK encoding (default)
ws.SyncSendText "中文测试", 5000, , , wcpAcp
' Use UTF-8 encoding (recommended)
ws.SyncSendText "中文测试", 5000, , , wcpUtf8
' Use Unicode (no conversion)
ws.SyncSendText "中文测试", 5000, , , wcpUnicodeSyncSendArray - Synchronous Send Byte Array
Description
Synchronously send byte array data with timeout control.
Syntax
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 BooleanParameters
| Parameter | Type | Description |
|---|---|---|
Buffer | Byte() | Byte array to send |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Target host address |
HostPort | Long (Optional) | Target port |
Flags | Long (Optional) | Send flags |
Return Value
True- Send successfulFalse- Send failed or timed out
Usage Example
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 SubSyncSend - Synchronous Send Buffer
Description
Synchronously send data from a specified buffer pointer, for high-performance scenarios.
Syntax
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 BooleanParameters
| Parameter | Type | Description |
|---|---|---|
BufPtr | Long | Buffer pointer |
BufLen | Long | Buffer length |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Target host address |
HostPort | Long (Optional) | Target port |
Flags | Long (Optional) | Send flags |
Return Value
True- Send successfulFalse- Send failed or timed out
Usage Example
' 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 SubSyncReceiveText - Synchronous Receive Text
Description
Synchronously receive text data with timeout control. Can specify the minimum number of bytes to receive.
Syntax
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 StringParameters
| Parameter | Type | Description |
|---|---|---|
NeedLen | Long (Optional) | Minimum bytes to receive, default 1 |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Source host address (for UDP mode) |
HostPort | Long (Optional) | Source port (for UDP mode) |
CodePage | EnumScpCodePage (Optional) | Text encoding, default wcpUtf8 |
Return Value
- Success: Returns received text
- Failure: Returns empty string
Usage Example
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 SubRead Fixed Length
' Read first 100 bytes
Dim sHeader As String
sHeader = ws.SyncReceiveText(100, 3000, , , wcpUtf8)
Debug.Print "Header: " & sHeaderSyncReceiveArray - Synchronous Receive Byte Array
Description
Synchronously receive byte array data with timeout control.
Syntax
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 BooleanParameters
| Parameter | Type | Description |
|---|---|---|
Buffer | Byte() | Byte array to receive data |
NeedLen | Long (Optional) | Minimum bytes to receive |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Source host address |
HostPort | Long (Optional) | Source port |
Flags | Long (Optional) | Receive flags |
Return Value
True- Receive successfulFalse- Receive failed or timed out
Usage Example
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 SubSyncReceive - Synchronous Receive to Buffer
Description
Synchronously receive data from socket to a specified buffer pointer, for high-performance scenarios.
Syntax
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 BooleanParameters
| Parameter | Type | Description |
|---|---|---|
BufPtr | Long | Buffer pointer |
BufLen | Long | Buffer length |
Received | Long (ByRef) | Actual bytes received |
TimeOut | Long (Optional) | Timeout in milliseconds |
HostAddress | String (Optional) | Source host address |
HostPort | Long (Optional) | Source port |
Flags | Long (Optional) | Receive flags |
Return Value
True- Receive successful,Receivedcontains actual bytes receivedFalse- Receive failed or timed out
Usage Example
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 SubSyncWaitForEvent - 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
Public Function SyncWaitForEvent( _
ByVal TimeOut As Long, _
Optional ByVal EventMask As WinSocketEventMaskEnum = wskSfdAll) As BooleanParameters
| Parameter | Type | Description |
|---|---|---|
TimeOut | Long | Timeout in milliseconds |
EventMask | WinSocketEventMaskEnum (Optional) | Event mask, default wskSfdAll |
Return Value
True- Specified event occurredFalse- Timeout or error
Usage Example
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 SubWait for Multiple Events
' 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 IfSyncCancelWait - Cancel Wait
Description
Cancel the currently running synchronous wait operation (such as SyncWaitForEvent, SyncReceiveText, etc.).
Syntax
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
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 SubUsage Scenarios
Scenario 1: HTTP Client
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 sHtmlScenario 2: Echo Client
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 SubScenario 3: File Upload (Simplified)
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 SubAsync 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
' 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 SubSync 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
' 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 SubSelection Recommendations
| Scenario | Recommended Mode | Reason |
|---|---|---|
| Simple HTTP client | Sync | Sequential operations, simple logic |
| TCP server | Async | Need to handle multiple clients |
| High-concurrency applications | Async | Avoid blocking |
| Rapid prototyping | Sync | Fast development |
| File transfer | Sync | Simple request-response |
| Real-time communication | Async | Timely response |
Important Notes
⚠️ Important Considerations
Message Pump Mechanism
- Synchronous methods use
PeekMessage/DispatchMessageinternally to process message queue - Does not block UI message loop, forms can still respond
- No need to manually call
DoEvents
- Synchronous methods use
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
Error Handling
- All synchronous methods should be used with
On Error - Check return value to determine if operation was successful
- Use
GetErrorDescriptionto get error description
- All synchronous methods should be used with
Resource Cleanup
- Be sure to call
Close_after operations complete - Cancel ongoing wait operations when form unloads
- Use
SyncCancelWaitto interrupt long waits
- Be sure to call
Encoding Issues
- Default encoding is
wcpUtf8 - Ensure send and receive use the same encoding
- Clearly specify encoding protocol when communicating with other systems
- Default encoding is
State Checking
- Ensure socket is connected before calling synchronous methods
- Use
Stateproperty to check connection status - Use
BytesReceivedto check available data
⚠️ Performance Considerations
Avoid Frequent Small Data Sends
- Merge small data blocks together
- Use buffer for batch processing
Set Reasonable Timeout
- Too short timeout may cause false judgments
- Too long timeout reduces response speed
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
' 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 SubSimple Chat Client Example
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 SubSummary
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