Skip to content

cWinsock Methods Reference ​

📋 Method List ​

Method NameReturn TypeDescription
ConnectSubConnect to remote server
ListenSubStart listening on port
BindSubBind local port (UDP)
SendDataSubSend data
GetDataSubReceive data
PeekDataSubPeek at data without removing
Close_SubClose connection
GetErrorDescriptionStringGet error description
AcceptFromSubAccept connection (internal method)
SetUdpClientInfoSubSet UDP client info (internal method)
RemoveClientSubRemove client (internal method)
RaiseDataArrivalEventSubTrigger data arrival event (internal method)

🔗 Connect Method ​

Description ​

Connect to the specified remote server (TCP client mode).

Syntax ​

vb
Public Sub Connect(Optional RemoteHost As String, Optional ByVal RemotePort As Long)

Parameters ​

ParameterTypeDescription
RemoteHostString (optional)Remote hostname or IP address. If not provided, uses RemoteHost property value
RemotePortLong (optional)Remote port number. If not provided, uses RemotePort property value

Usage Example ​

vb
' Connect using parameters
m_oClient.Connect "127.0.0.1", 8080

' Connect using properties
m_oClient.RemoteHost = "example.com"
m_oClient.RemotePort = 80
m_oClient.Connect

' Connect to specific host
m_oClient.RemoteHost = "192.168.1.100"
m_oClient.Connect , 8080  ' Only specify port, use already set RemoteHost

Connection Flow ​

1. Call Connect()
2. Close existing connection (if any)
3. Resolve hostname → sckResolvingHost
4. Hostname resolved → sckHostResolved
5. Start connecting → sckConnecting
6. Connection successful → sckConnected
7. Trigger Connect event

Error Handling ​

vb
Private Sub cmdConnect_Click()
    On Error GoTo EH
    
    m_oClient.Connect "example.com", 8080
    Exit Sub
    
EH:
    Debug.Print "Connection error: " & Err.Description
    Select Case Err.Number
        Case 10060
            MsgBox "Connection timeout, please check network"
        Case 10061
            MsgBox "Server refused connection, please check port"
        Case Else
            MsgBox "Connection failed: " & Err.Description
    End Select
End Sub

🎧 Listen Method ​

Description ​

Start listening on the specified port, waiting for client connections (TCP server mode).

Syntax ​

vb
Public Sub Listen(Optional ByVal Port As Long)

Parameters ​

ParameterTypeDescription
PortLong (optional)Port number to listen on. If not provided, uses LocalPort property value

Usage Example ​

vb
' Listen using parameter
m_oServer.Listen 8080

' Listen using property
m_oServer.LocalPort = 8080
m_oServer.Listen

' Listen on multiple ports (need multiple cWinsock objects)
Dim oServer1 As New cWinsock
Dim oServer2 As New cWinsock
oServer1.Listen 8080
oServer2.Listen 8081

Server Startup Flow ​

vb
Private Sub StartServer()
    On Error GoTo EH
    
    ' Set protocol
    m_oServer.Protocol = sckTCPProtocol
    
    ' Start listening
    m_oServer.Listen 8080
    
    Debug.Print "Server started, listening on port: " & m_oServer.LocalPort
    
    ' Update UI
    btnStart.Enabled = False
    btnStop.Enabled = True
    lblStatus.Caption = "Listening..."
    
    Exit Sub
    
EH:
    Debug.Print "Failed to start server: " & Err.Description
    MsgBox "Cannot start server: " & Err.Description, vbExclamation
End Sub

⚠️ Notes ​

  • Must set Protocol = sckTCPProtocol before calling Listen()
  • Port must not be already in use
  • State will become sckListening

📌 Bind Method ​

Description ​

Bind to local port (UDP server mode).

Syntax ​

vb
Public Sub Bind(Optional ByVal LocalPort As Long, Optional LocalIP As String)

Parameters ​

ParameterTypeDescription
LocalPortLong (optional)Local port number to bind
LocalIPString (optional)Local IP address to bind (optional)

Usage Example ​

vb
' Bind port
m_oUdp.Protocol = sckUDPProtocol
m_oUdp.Bind 8888

' Bind to specific IP
m_oUdp.Bind 8888, "192.168.1.100"

UDP Server Startup ​

vb
Private Sub StartUdpServer()
    On Error GoTo EH
    
    ' Set protocol
    m_oUdp.Protocol = sckUDPProtocol
    
    ' Bind port
    m_oUdp.Bind 8888
    
    Debug.Print "UDP server started, bound to port: " & m_oUdp.LocalPort
    
    Exit Sub
    
EH:
    Debug.Print "UDP bind failed: " & Err.Description
    MsgBox "Cannot bind UDP port: " & Err.Description, vbExclamation
End Sub

📤 SendData Method ​

Description ​

Send data to remote host.

Syntax ​

vb
Public Sub SendData(Data As Variant, Optional ByVal CodePage As EnumScpCodePage = ScpAcp)

Parameters ​

ParameterTypeDescription
DataVariantData to send, can be string or byte array
CodePageEnumScpCodePage (optional)Text encoding, default ScpAcp (GBK/ACP)

Encoding Options ​

ConstantValueDescription
ScpAcp0System default code page (GBK on Chinese Windows)
ScpOem1OEM code page
ScpUtf865001UTF-8 encoding
ScpUnicode-1Unicode, no encoding conversion

Sending String ​

vb
' Default uses ACP/GBK encoding
m_oClient.SendData "中文测试"

' Use UTF-8 encoding
m_oClient.SendData "中文测试", ScpUtf8

' Use Unicode (no conversion)
m_oClient.SendData "中文测试", ScpUnicode

Sending Byte Array ​

vb
' Send byte array
Dim baData() As Byte
baData = GetBinaryData()
m_oClient.SendData baData

UDP Server Sending ​

vb
' In UDP server mode, need to specify remote address
Private Sub cmdUdpSend_Click()
    ' Set target
    m_oUdp.RemoteHost = "127.0.0.1"
    m_oUdp.RemotePort = 9999
    
    ' Send data
    m_oUdp.SendData "Hello, UDP!"
End Sub

' Reply to specific client (virtual client)
Private Sub m_oUdp_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sData As String
    Client.GetData sData
    
    ' Reply directly through Client object
    ' cWinsock automatically uses correct remote address:port
    Client.SendData "Reply: " & sData
End Sub

Large Data Sending ​

vb
' Send large data in chunks
Private Sub SendLargeFile(ByVal sFilePath As String)
    Dim baChunk() As Byte
    Dim lChunkSize As Long
    lChunkSize = 8192 ' 8KB per chunk
    
    ' Open file...
    ' Loop read and send
    Do While Not EOF
        ' Read data chunk
        ReadChunk baChunk, lChunkSize
        
        ' Send
        m_oClient.SendData baChunk
        
        ' Wait for send completion (via SendComplete event)
        Do While m_bSending
            DoEvents
        Loop
    Loop
End Sub

📥 GetData Method ​

Description ​

Read data from receive buffer.

Syntax ​

vb
Public Sub GetData(Data As Variant, Optional ByVal VarType_ As Long, Optional ByVal MaxLen As Long = -1, Optional ByVal CodePage As EnumScpCodePage = ScpAcp)

Parameters ​

ParameterTypeDescription
DataVariantVariable to receive data
VarType_Long (optional)Expected data type (e.g., vbString, vbByte + vbArray)
MaxLenLong (optional)Maximum bytes to read, -1 means read all
CodePageEnumScpCodePage (optional)Text encoding, default ScpAcp

Reading String ​

vb
Private Sub m_oClient_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sData As String
    
    ' Read all data
    Client.GetData sData
    
    Debug.Print "Received: " & 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"
End Sub

Partial Reading ​

vb
Private Sub m_oClient_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
    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, ScpUtf8
    
    Debug.Print "UTF-8 data: " & sData
End Sub

Protocol Parsing ​

vb
Private Type tPacketHeader
    Magic As Long ' Magic number
    Length As Long ' Data length
    Type As Long ' Data type
End Type

Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim tHeader As tPacketHeader
    Dim baBody() As Byte
    
    ' Read header
    Client.GetData tHeader
    
    ' Verify magic number
    If tHeader.Magic = &H12345678 Then
        ' Read data body
        ReDim baBody(0 To tHeader.Length - 1) As Byte
        Client.GetData baBody
        
        Debug.Print "Data type: " & tHeader.Type
        Debug.Print "Data length: " & tHeader.Length
    End If
End Sub

👁️ PeekData Method ​

Description ​

Peek at data without removing from buffer.

Syntax ​

vb
Public Sub PeekData(Data As Variant, Optional ByVal VarType_ As Long, Optional ByVal MaxLen As Long = -1, Optional ByVal CodePage As EnumScpCodePage = ScpAcp)

Parameters ​

Same as GetData.

Usage Example ​

vb
Private Sub m_oClient_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sPeek As String
    Dim sActual As String
    
    ' Peek at data first
    Client.PeekData sPeek
    Debug.Print "Peek data: " & sPeek
    
    ' Then read data
    Client.GetData sActual
    Debug.Print "Actual data: " & sActual
End Sub

Protocol Detection ​

vb
Private Sub m_oServer_DataArrival(Client As cWinsock, ByVal bytesTotal As Long)
    Dim sPeek As String
    
    ' Peek at first few characters to detect protocol
    Client.PeekData sPeek, vbString, 4
    
    If Left$(sPeek, 4) = "HTTP" Then
        Debug.Print "HTTP request"
        HandleHttpRequest Client
    ElseIf Left$(sPeek, 4) = "CHAT" Then
        Debug.Print "Chat protocol"
        HandleChatMessage Client
    Else
        Debug.Print "Unknown protocol"
    End If
End Sub

🔒 Close_ Method ​

Description ​

Close connection or stop listening.

Syntax ​

vb
Public Sub Close_()

Usage Example ​

vb
' Close client connection
Private Sub cmdDisconnect_Click()
    m_oClient.Close_
    Debug.Print "Disconnected"
End Sub

' Stop server
Private Sub cmdStopServer_Click()
    m_oServer.Close_
    Debug.Print "Server stopped"
End Sub

' Close specific client
Private Sub DisconnectClient(ByVal oClient As cWinsock)
    oClient.Close_
    m_oServer.RemoveClient oClient
End Sub

Auto Close ​

vb
' Auto close when form unloads
Private Sub Form_Unload(Cancel As Integer)
    On Error Resume Next
    m_oClient.Close_
    m_oServer.Close_
    m_oUdp.Close_
End Sub

📝 GetErrorDescription Method ​

Description ​

Get description of error code.

Syntax ​

vb
Public Function GetErrorDescription(ByVal ErrorCode As Long) As String

Usage Example ​

vb
Private Sub m_oClient_Error(Client As cWinsock, ByVal Number As Long, Description As String, ByVal Scode As Long)
    ' Use description from parameter
    Debug.Print "Error: " & Description
    
    ' Or use GetErrorDescription to get
    Debug.Print "Error description: " & Client.GetErrorDescription(Number)
End Sub

' Independent use
Dim sDesc As String
sDesc = m_oClient.GetErrorDescription(10060)
Debug.Print sDesc ' "Connection timeout"

🤝 Friend Methods ​

The following methods are for internal use, usually don't need to call directly:

AcceptFrom ​

Accept new connection (called by OnAccept event).

SetUdpClientInfo ​

Set UDP virtual client info (called by OnReceive event).

RemoveClient ​

Remove client (called by CloseEvent or manually).

RaiseDataArrivalEvent ​

Trigger data arrival event (called by client object, triggered through parent server).


📌 Method Usage Scenarios Summary ​

TCP Client Flow ​

vb
1. m_oClient.Connect("127.0.0.1", 8080)
2. Wait for m_oClient_Connect event
3. m_oClient.SendData("Hello")
4. Wait for m_oClient_DataArrival event
5. Client.GetData sData
6. m_oClient.Close_()

TCP Server Flow ​

vb
1. m_oServer.Listen(8080)
2. Wait for m_oServer_ConnectionRequest event
3. Set DisConnect = False to accept
4. Wait for m_oServer_DataArrival event
5. Client.GetData sData
6. Client.SendData("Reply")
7. Wait for m_oServer_CloseEvent event

UDP Flow ​

vb
1. m_oUdp.Bind(8888)
2. Wait for m_oUdp_DataArrival event
3. Client.GetData sData
4. Client.SendData("Reply")
5. m_oUdp.Close_()

Last Updated: 2026-01-09

VB6 and LOGO copyright of Microsoft Corporation