Winsock Control

The Winsock control, invisible to the user, provides easy access to TCP and UDP network services. It can be used by Microsoft Access, Visual Basic, Visual C++, or Visual FoxPro developers. To write client or server applications you do not need to understand the details of TCP or to call low level Winsock APIs. By setting properties and invoking methods of the control, you can easily connect to a remote machine and exchange data in both directions.

TCP Basics

The Transfer Control Protocol allows you to create and maintain a connection to a remote computer. Using the connection, both computers can stream data between themselves.

If you are creating a client application, you must know the server computer's name or IP address (RemoteHost property), as well as the port (RemotePort property) on which it will be "listening." Then invoke the Connect method.

If you are creating a server application, set a port (LocalPort property) on which to listen, and invoke the Listen method. When the client computer requests a connection, the ConnectionRequest event will occur. To complete the connection, invoke the Accept method within the ConnectionRequest event.

Once a connection has been made, either computer can send and receive data. To send data, invoke the SendData method. Whenever data is received, the DataArrival event occurs. Invoke the GetData method within the DataArrival event to retrieve the data.

UDP Basics

The User Datagram Protocol (UDP) is a connectionless protocol. Unlike TCP operations, computers do not establish a connection. Also, a UDP application can be either a client or a server.

To transmit data, first set the client computer's LocalPort property. The server computer then needs only to set the RemoteHost to the Internet address of the client computer, and the RemotePort property to the same port as the client computer's LocalPort property, and invoke the SendData method to begin sending messages. The client computer then uses the GetData method within the DataArrival event to retrieve the sent messages.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Close Event

Occurs when the remote computer closes the connection. Applications should use the Close method to correctly close a TCP connection.

Syntax

object_Close( )

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Arguments

None


Connect Event (Winsock Control)

Occurs when a Connect operation is completed.

Syntax

object.Connect()

The object placeholder represents an object expression that evaluates to a Winsock control.

Remarks

Use the Connect event to confirm when a connection has been made successfully.


ConnectionRequest Event

Occurs when a remote machine requests a connection.

  • For TCP server applications only. The event is activated when there is an incoming connection request. RemoteHostIP and RemotePort properties store the information about the client after the event is activated.

Syntax

object_ConnectionRequest (requestID As Long)

The ConnectionRequest event syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
requestID | The incoming connection request identifier. This argument should be passed to the Accept method on the second control instance.

Remarks

The server can decide whether or not to accept the connection. If the incoming connection is not accepted, the peer (client) will get the Close event. Use the Accept method (on a new control instance) to accept an incoming connection.


DataArrival Event

Occurs when new data arrives.

Syntax

object_DataArrival (bytesTotal As Long)

The DataArrival event syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
bytesTotal | Long. The total amount of data that can be retrieved.

Remarks

This event will not occur if you do not retrieve all the data in one GetData call. It is activated only when there is new data. Use the BytesReceived property to check how much data is available at any time.


Error Event (Winsock Control)

Occurs whenever an error occurs in background processing (for example, failed to connect, or failed to send or receive in the background).

Syntax

object_Error(number As Integer, Description As String, Scode As Long, Source As String, HelpFile as String, HelpContext As Long, CancelDisplay As Boolean)

The Error event syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
number | An integer that defines the error code. See Settings below for constants.
description | String containing error information.
Scode | The long SCODE
Source | String describing the error source.
HelpFile | String containing the help file name.
HelpContext | Help file context.
CancelDisplay | Indicates whether to cancel the display. The default is False, which is to display the default error message box. If you do not want to use the default message box, set CancelDisplay to True.

Settings

The settings for number are:

Constant | Value | Description
sckOutOfMemory | 7 | Out of memory
sckInvalidPropertyValue | 380 | The property value is invalid.
sckGetNotSupported | 394 | The property can't be read.
sckSetNotSupported | 383 | The property is read-only.
sckBadState | 40006 | Wrong protocol or connection state for the requested transaction or request.
sckInvalidArg | 40014 | The argument passed to a function was not in the correct format or in the specified range.
sckSuccess | 40017 | Successful.
sckUnsupported | 40018 | Unsupported variant type.
sckInvalidOp | 40020 | Invalid operation at current state
sckOutOfRange | 40021 | Argument is out of range.
sckWrongProtocol | 40026 | Wrong protocol for the requested transaction or request
sckOpCanceled | 1004 | The operation was canceled.
sckInvalidArgument | 10014 | The requested address is a broadcast address, but flag is not set.
sckWouldBlock | 10035 | Socket is non-blocking and the specified operation will block.
sckInProgress | 10036 | A blocking Winsock operation in progress.
sckAlreadyComplete | 10037 | The operation is completed. No blocking operation in progress
sckNotSocket | 10038 | The descriptor is not a socket.
sckMsgTooBig | 10040 | The datagram is too large to fit into the buffer and is truncated.
sckPortNotSupported | 10043 | The specified port is not supported.
sckAddressInUse | 10048 | Address in use.
sckAddressNotAvailable | 10049 | Address not available from the local machine.
sckNetworkSubsystemFailed | 10050 | Network subsystem failed.
sckNetworkUnreachable | 10051 | The network cannot be reached from this host at this time.
sckNetReset | 10052 | Connection has timed out when SO_KEEPALIVE is set.
sckConnectAborted | 11053 | Connection is aborted due to timeout or other failure.
sckConnectionReset | 10054 | The connection is reset by remote side.
sckNoBufferSpace | 10055 | No buffer space is available.
sckAlreadyConnected | 10056 | Socket is already connected.
sckNotConnected | 10057 | Socket is not connected.
sckSocketShutdown | 10058 | Socket has been shut down.
sckTimedout | 10060 | Socket has been shut down.
sckConnectionRefused | 10061 | Connection is forcefully rejected.
sckNotInitialized | 10093 | WinsockInit should be called first.
sckHostNotFound | 11001 | Authoritative answer: Host not found.
sckHostNotFoundTryAgain | 11002 | Non-Authoritative answer: Host not found.
sckNonRecoverableError | 11003 | Non-recoverable errors.
sckNoData | 11004 | Valid name, no data record of requested type.


SendComplete Event

Occurs when a send operation is completed.

Syntax

object_SendComplete

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Arguments

None


SendProgress Event

Occurs while data is being sent.

Syntax

object_SendProgress (bytesSent As Long, bytesRemaining As Long)

The SendProgress event syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
bytesSent | The number of bytes that have been sent since the last time this event was activated.
bytesRemaining | The number of bytes in the send buffer waiting to be sent.


Accept Method

For TCP server applications only. This method is used to accept an incoming connection when handling a ConnectionRequest event.

Syntax

object.Accept requestID

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

Long

Return Value

Void

Remarks

The Accept method is used in the ConnectionRequest event. The ConnectionRequest event has a corresponding argument, the RequestID parameter, that should be passed to the Accept method. An example is shown below:

Private Sub Winsock1_ConnectionRequest _
(ByVal requestID As Long)
   ' Close the connection if it is currently open
   ' by testing the State property.
   If Winsock1.State <> sckClosed Then Winsock1.Close

   ' Pass the value of the requestID parameter to the
   ' Accept method.
   Winsock1.Accept requestID
End Sub

The Accept method should be used on a new control instance (other than the one that is in the listening state.)


Accept Method, ConnectionRequest Event Example (Visual Basic)

Accept Method, ConnectionRequest Event Example

The example shows the code necessary to connect a Winsock control using the TCP protocol. The code runs on the machine that is accepting the connection request. The RequestID parameter identifies the request. This is passed to the Accept method which accepts the particular request.

Private Sub WinsockTCP_ConnectionRequest _
(requestID As Long)
   If Winsock1.State <> sckClosed Then Winsock1.Close
   Winsock.Accept requestID
End Sub


Bind Method

Specifies the LocalPort and LocalIP to be used for TCP connections. Use this method if you have multiple protocol adapters.

Syntax

object.Bind LocalPort, LocalIP

The Bind method syntax has these parts

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
LocalPort | The port used to make a connection.
LocalIP | The local Internet address used to make a connection.

Remarks

You must invoke the Bind method before invoking the Listen method.


Close Method (Winsock Control)

Closes a TCP connection or a listening socket for both client and server applications.

Syntax

object.Close

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Arguments

None

Return Value

Void


Connect Method

Requests a connection to a remote computer.

Syntax

object.Connect remoteHost, remotePort

The Connect method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
remoteHost | Required. The name of the remote computer to connect to.
remotePort | The port of the remote computer to connect to.

Return Value

None

Remarks

You must invoke the Connect method when attempting to establish a TCP connection.


GetData Method (WinSock Control), DataArrival Event Example (Visual Basic)

GetData Method (WinSock Control), DataArrival Event Example

The example uses the GetData method in the DataArrival event of a Winsock control. When the event occurs, the code invokes the GetData method to retrieve the data and store it in a string variable. The data is then written into a TextBox control.

Private Sub Winsock1_DataArrival _
(ByVal bytesTotal As Long)
   Dim strData As String
   Winsock1.GetData strData, vbString
   Text1.Text = Text1.Text & strData
End Sub


GetData Method (WinSock Control)

Retrieves the current block of data and stores it in a variable of type variant.

Return Value

Void

Syntax

object.GetData data, [type,] [maxLen]

The GetData method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
data | Where retrieved data will be stored after the method returns successfully. If there is not enough data available for requested type, data will be set to Empty.
type | Optional. Type of data to be retrieved, as shown in Settings.
maxLen | Optional. Specifies the desired size when receiving a byte array or a string. If this parameter is missing for byte array or string, all available data will be retrieved. If provided for data types other than byte array and string, this parameter is ignored.

Settings

The settings for type are:

Description | Constant
Byte | vbByte
Integer | vbInteger
Long | vbLong
Single | vbSingle
Double | vbDouble
Currency | vbCurrency
Date | vbDate
Boolean | vbBoolean
SCODE | vbError
String | vbString
Byte Array | vbArray + vbByte

Remarks

It's common to use the GetData method with the DataArrival event, which includes the totalBytes argument. If you specify a maxlen that is less than the totalBytes argument, you will get the warning 10040 indicating that the remaining bytes will be lost.


Listen Method

Creates a socket and sets it in listen mode. This method works only for TCP connections.

Syntax

object.Listen

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Arguments

None

Return Value

Void

Remarks

The ConnectionRequest event occurs when there is an incoming connection. When handling ConnectionRequest, the application should use the Accept method (on a new control instance) to accept the connection.


PeekData Method

Similar to GetData except PeekData does not remove data from the input queue. This method works only for TCP connections.

Syntax

object.PeekData data, [type,] [maxLen]

The PeekData method syntax has these parts

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
data | Stores retrieved data after the method returns successfully. If there is not enough data available for requested type, data will be set to Empty.
type | Optional. Type of data to be retrieved, as described in Settings. Default Value: vbArray + vbByte.
maxLen | Optional. Length specifies the desired size when receiving a byte array or a string. If this argument is missing for byte array or string, all available data will be retrieved. If provided for data types other than byte array and string, this argument is ignored.

Settings

The settings for type are:

Type | Constant
Byte | vbByte
Integer | vbInteger
Long | vbLong
Single | vbSingle
Double | vbDouble
Currency | vbCurrency
Date | vbDate
Boolean | vbBoolean
SCODE | vbError
String | vbString
Byte Array | vbArray + vbByte

Return Value

Void

Remarks

If the type is specified as vbString, string data is converted to UNICODE before returning to the user.


SendData Method

Sends data to a remote computer.

Return Value

Void

Syntax

object.SendData data

The SendData method syntax has these parts

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
data | Data to be sent. For binary data, byte array should be used.

Remarks

When a UNICODE string is passed in, it is converted to an ANSI string before being sent out on the network.


BytesReceived Property

Returns the amount of data received (currently in the receive buffer). Use the GetData method to retrieve data.

Read-only and unavailable at design time.

Syntax

object.BytesReceived

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Value

Long


LocalHostName Property

Returns the local machine name. Read-only and unavailable at design time.

Syntax

object.LocalHostName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Value

String


LocalIP Property

Returns the IP address of the local machine in the IP address dotted string format (xxx.xxx.xxx.xxx).Read-only and unavailable at design time.

Syntax

object.LocalIP

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

String


LocalPort Property

Returns or sets the local port to use. Read/Write and available at design time.

  • For the client, this designates the local port to send data from. Specify port 0 if the application does not need a specific port. In this case, the control will select a random port. After a connection is established, this is the local port used for the TCP connection.

  • For the server, this is the local port to listen on. If port 0 is specified, a random port is used. After invoking the Listen method, the property contains the actual port that has been selected.

Syntax

object.LocalPort = long

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

Long

Remarks

Port 0 is often used to establish connections between computers dynamically. For example, a client that wishes to be "called back" by a server can use port 0 to procure a new (random) port number, which can then be given to the remote computer for this purpose.


Protocol Property (Winsock Control)

Returns or sets the protocol, either TCP or UDP, used by the Winsock control.

Syntax

object.Protocol [=protocol]

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The settings for protocol are:

Constant | Value | Description
sckTCPProtocol | 0 | Default. TCP protocol.
sckUDPProtocol | 1 | UDP protocol.

Return Value

Void

Remarks

The control must be closed (using the Close method) before this property can be reset.


RemoteHostIP Property

Returns the IP address of the remote machine.

  • For client applications, after a connection has been established using the Connect method, this property contains the IP string of the remote machine.

  • For server applications, after an incoming connection request (ConnectionRequest event), this property contains the IP string of the remote machine that initiated the connection.

  • When using the UDP protocol, after the DataArrival event occurs, this property contains the IP address of the machine sending the UDP data.

Syntax

object.RemoteHostIP

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

String


SocketHandle Property

Returns a value that corresponds to the socket handle the control uses to communicate with the Winsock layer. Read-only and unavailable at design time.

Syntax

object.SocketHandle

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

Long

Remarks

This property was designed to be passed to Winsock APIs.


State Property (Winsock Control)

Returns the state of the control, expressed as an enumerated type. Read-only and unavailable at design time.

Syntax

object.State

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Data Type

Integer

Settings

The settings for the State property are:

Constant | Value | Description
sckClosed | 0 | Default. Closed
sckOpen | 1 | Open
sckListening | 2 | Listening
sckConnectionPending | 3 | Connection pending
sckResolvingHost | 4 | Resolving host
sckHostResolved | 5 | Host resolved
sckConnecting | 6 | Connecting
sckConnected | 7 | Connected
sckClosing | 8 | Peer is closing the connection
sckError | 9 | Error