VB6 Winsock Networking

VB6 Winsock Networking The Winsock control in VB6 provides TCP and UDP networking. This tutorial builds a simple chat client and server. Adding the Winsock Control Go to Project → Components . Check Microsoft Winsock Control 6.0 . Click OK . The Winsock icon appears in the Toolbo

FDN » Visual Basic » VB6 Winsock Networking

VB6 Winsock Networking

The Winsock control in VB6 provides TCP and UDP networking. This tutorial builds a simple chat client and server.

Adding the Winsock Control

  1. Go to Project → Components.
  2. Check Microsoft Winsock Control 6.0.
  3. Click OK. The Winsock icon appears in the Toolbox.

TCP Server

' Form: frmServer
' Controls: Winsock1 (listening), Winsock2 (client connection), txtLog (TextBox)
Private Sub Form_Load()
    Winsock1.LocalPort = 5000
    Winsock1.Listen
    LogMsg "Server listening on port 5000..."
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
    If Winsock2.State <> sckClosed Then Winsock2.Close
    Winsock2.Accept requestID
    LogMsg "Client connected from " & Winsock2.RemoteHostIP
End Sub

Private Sub Winsock2_DataArrival(ByVal bytesTotal As Long)
    Dim strData As String
    Winsock2.GetData strData
    LogMsg "Client: " & strData
    ' Echo back
    Winsock2.SendData "Echo: " & strData
End Sub

Private Sub Winsock2_Close()
    Winsock2.Close
    LogMsg "Client disconnected."
End Sub

Private Sub LogMsg(ByVal msg As String)
    txtLog.Text = txtLog.Text & FormatDateTime(Now, vbShortTime) & " " & msg & vbCrLf
End Sub

TCP Client

' Form: frmClient
' Controls: Winsock1, txtMessage, cmdSend, txtLog

Private Sub Form_Load()
    Winsock1.RemoteHost = "192.168.1.10"
    Winsock1.RemotePort = 5000
    Winsock1.Connect
End Sub

Private Sub Winsock1_Connect()
    LogMsg "Connected to server."
End Sub

Private Sub cmdSend_Click()
    If Winsock1.State = sckConnected Then
        Winsock1.SendData txtMessage.Text
        LogMsg "Sent: " & txtMessage.Text
        txtMessage.Text = ""
    End If
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim strData As String
    Winsock1.GetData strData
    LogMsg "Server: " & strData
End Sub

Key Properties and Events

Property/EventDescription
ProtocolsckTCPProtocol (default) or sckUDPProtocol
LocalPortPort to listen on (server)
RemoteHostIP or hostname to connect to (client)
RemotePortPort to connect to (client)
ConnectionRequestFires when a client connects (server)
DataArrivalFires when data is received
SendCompleteFires when data has been sent
« Developer Network ‹ Creating ActiveX Controls Deploying VB Applications ›